【LeetCode】38.Combination Sum

来源:互联网 发布:云盘 php源码 编辑:程序博客网 时间:2024/05/29 19:57

Description:

Given a set of candidate numbers (C(without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is: 

[  [7],  [2, 2, 3]]

题目思考:

 使用递归向下查找数组,每次找到一个,减去继续找到子集再进行拼接。

避免重复,新的数字必须不能在当前数字的前面。


 Solution:

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        return combinationSum(candidates, target, 0);
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target, int beg) {
        vector<vector<int>> ret;
        if (target <= 0) {return ret;}
        for (int i = beg; i < candidates.size(); i++) {
            int iv = candidates[i];
            vector<int> one;
            if (iv == target) {
                one.push_back(iv);
                ret.push_back(one);
            }
            
            vector<vector<int>> suf = combinationSum(candidates, target-iv, i);
            for (int j = 0; j < suf.size(); j++) {
                suf[j].push_back(iv);
                ret.push_back(suf[j]);
            }
        }
        return ret;
    }
};

原创粉丝点击