【leetcode】39. Combination Sum 求整数数组里的等于指定值的所有子集

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
    原文地址: https://segmentfault.com/a/1190000007300946
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞