zoukankan      html  css  js  c++  java
  • 40. Combination Sum II **

    description:

    给定target, 求给定数列中找到几个数(其中的数不可以重复使用,且一组数有几个也不做限制)的和为target,和上面那个题一毛一样的,就改一下下标就行了,背下来背下来背下来~~~
    Note:

    All numbers (including target) will be positive integers.
    The solution set must not contain duplicate combinations. //这个条件注意了,只要是两个挨着的一样,那么就会导致最后出现相同的组合
    

    Example:

    Example 1:
    
    Input: candidates = [10,1,2,7,6,1,5], target = 8,
    A solution set is:
    [
      [1, 7],
      [1, 2, 5],
      [2, 6],
      [1, 1, 6]
    ]
    
    Example 2:
    
    Input: candidates = [2,5,2,1,2], target = 5,
    A solution set is:
    [
      [1,2,2],
      [5]
    ]
    

    answer:

    class Solution {
    public:
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            vector<vector<int>> res;
            vector<int> out;
            sort(candidates.begin(), candidates.end()); //这里刚开始就没写,一定要先变成有序数组!!!
            combinationDFS(candidates, res, out, target, 0);
            return res;
        }
        void combinationDFS(vector<int>& candidates, vector<vector<int>>& res, vector<int>& out, int target, int start) {
            if(target < 0) return;
            if(target == 0) {
                res.push_back(out);
                return;
            }
            for(int i = start; i < candidates.size(); i++) {
                if(i > start && candidates[i] == candidates[i - 1]) continue; //这里也要注意了,因为上边那个note的第二条
                out.push_back(candidates[i]);
                combinationDFS(candidates, res, out, target - candidates[i], i + 1);
                out.pop_back();
            }
        }
    };
    

    relative point get√:

    hint :

  • 相关阅读:
    redis的rpm包下载安装
    linux下创建普通用户并赋予某个目录的读写权限
    nginx软件优化
    GIT分支简单操作
    mysqldump导入导出数据
    rsync守护进程方式同步实例-004
    rsync多模块配置&排除功能-003
    rsync数据同步方式-002
    rsync简单介绍-001
    Redis cluster 日常操作命令
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11166218.html
Copyright © 2011-2022 走看看