39. Combination Sum

题目

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]
]

分析

最简单的思路,就是通过对target减去candidates中的一个数来得到一个子问题。通过递归求解即可。还需要解决的一点是,这种方法会导致重复,所以需要在最后加入一个去重的部分,首先对每个解法中的数字排序,然后对所有解排序,最后去重得到结果。

实现一

class Solution {
public:
    vector> combinationSum(vector& candidates, int target) {
        vector> ans;
        ans = solve(candidates, target);
        for(int i=0; i> solve(vector& candidates, int target) {
        vector> ans;
        for(auto num: candidates){
            if(target-num<0){
                continue;
            }
            else if(target-num==0){
                ans.push_back({num});
            }
            else{
                vector> tmp;
                tmp = solve(candidates, target-num);
                if(tmp.empty())
                    continue;
                for(auto v: tmp){
                    v.push_back(num);
                    ans.push_back(v);
                }
            }
        }
        return ans;
    }
};

思考一

这种方法固然可行,但是由于重复的存在,会导致效率偏低。所以着手考虑优化。对每个子问题的解都进行去重可以缩短一部分时间,但是效果不是很明显。
较好的改进方法是,在递归的下一步时,只使用candidates中大于等于上一个使用的数字,这样就能保证所得的序列是递增的,也能保证其不重复。这样大大减少了运算时间。

实现二

class Solution {
public:
    vector> combinationSum(vector& candidates, int target) {
        vector> ans;
        ans = solve(candidates, target, 0);/*
        for(int i=0; i> solve(vector& candidates, int target, int start) {
        vector> ans;
        for(int i=start; i> tmp;
                tmp = solve(candidates, target-candidates[i], i);
                if(tmp.empty())
                    continue;
                for(auto v: tmp){
                    v.push_back(candidates[i]);
                    ans.push_back(v);
                }
            }
        }
        return ans;
    }
};

你可能感兴趣的:(39. Combination Sum)