1. 题目

Given a set of candidate numbers (C) 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]
]

2. 思路

递归的思路。
每次找到一个,然后target减去之后继续找到子集再拼接起来。
如果当前的直接满足就加入到返回结果中。
为了避免重复,递归向下查找时,新的数字必须不能在当前数字的前面即可。

3. 代码

耗时:33ms

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;
    }
};

knzeus
72 声望28 粉丝

行万里路,读万卷书