LeetCode Combination Sum

来源:互联网 发布:日本j2联赛网络直播 编辑:程序博客网 时间:2024/06/12 18:33

题目

Given a set of candidate numbers (C) and a target number (T), find all unique combinations inC 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 (a1,a2, … , ak) must be in non-descending order. (ie,a1a2 ≤ … ≤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]

 

求候选元素中所有和为目标值的组合,

候选元素可以多次取,组合不能完全相同。

虽然没有说明,实际所有的候选元素都是不同的。

递归求解。

 

代码:

class Solution {vector<vector<int>> ans;//结果vector<int> temp;//单次结果public:void combs(vector<int> &cand,int target,int sum,int begin)//候选集,目标,当前集合的和,当前集合用到的最大序号{if(sum==target)//符合要求{ans.push_back(temp);return;}for(int i=begin;i<cand.size();i++)//寻找{if(sum+cand[i]<=target){temp.push_back(cand[i]);combs(cand,target,sum+cand[i],i);temp.pop_back();}elsebreak;}}    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {        ans.clear();temp.clear();if(candidates.empty())return ans;sort(candidates.begin(),candidates.end());//!!!需要保证候选集合没有重复元素combs(candidates,target,0,0);return ans;    }};


 

 

 

 

 

 

 

0 0
原创粉丝点击