Combination Sum leetcode

来源:互联网 发布:广州java架构师培训 编辑:程序博客网 时间:2024/05/17 07:24

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.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 

这个题是一个NP问题,方法仍然是N-Queens中介绍的套路。基本思路是先排好序,然后每次递归中把剩下的元素一一加到结果集合中,并且把目标减去加入的元素,然后把剩下元素(包括当前加入的元素)放到下一层递归中解决子问题。算法复杂度因为是NP问题,所以自然是指数量级的。注意在实现中for循环中第一步有一个判断,那个是为了去除重复元素产生重复结果的影响,因为在这里每个数可以重复使用,所以重复的元素也就没有作用了,所以应该跳过那层递归。代码如下: 

class Solution {public:    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        vector<vector<int> > res;        if(candidates.size() == 0) {            return res;        }        sort(candidates.begin(),candidates.end());        vector<int> tmp;        findSum(res,candidates,tmp,0,target);        return res;    }    void findSum(vector<vector<int> >& res,vector<int>& candidates,vector<int>& tmp,int start,int target) {        if(target<0) {            return;        }else if(target == 0) {            res.push_back(tmp);            return;        } else {            for(int i=start;i<candidates.size();i++) {                if(i>start && candidates[i] == candidates[i-1]) {                    continue;                }                tmp.push_back(candidates[i]);                findSum(res,candidates,tmp,i,target-candidates[i]);                tmp.pop_back();            }        }    }};



0 0
原创粉丝点击