Combination Sum

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 (a1, a2, … , 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] 

思路:典型的DSF题目,对每一个元素进行选择,是否需要加入。该题目中每个元素可以出现多次。因此每个元素可以多次选择。

  1. public void combinationSumHelper(ArrayList<ArrayList<Integer> > res, ArrayList<Integer> cur,int[] candidates,int target,int start,int end) {
  2. if(target <= 0) {
  3. if(target == 0) {
  4. res.add(new ArrayList<Integer>(cur)); // must add the object
  5. }
  6. return ;
  7. }
  8. for(int i=start;i<=end;i++) {
  9. cur.add(candidates[i]);
  10. combinationSumHelper(res,cur,candidates,target-candidates[i],i,end);
  11. cur.remove(cur.size()-1);
  12. }
  13. }
  14. public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
  15. ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> >();
  16. if(candidates==null || candidates.length==0) return res;
  17. Arrays.sort(candidates);
  18. ArrayList<Integer> cur = new ArrayList<Integer>();
  19. combinationSumHelper(res,cur,candidates,target,0,candidates.length-1);
  20. return res;
  21. }

改进: 如果从当前值开始遍历,且当前值>start,且当前值 == 前一个值,则表明该值已经遍历完毕,可以直接进行下一个。

  1. vector<vector<int> > res;
  2. void combinationsSumHelper(vector<int> &candidates, int target,vector<int> &cur,int start) {
  3. if(start>=candidates.size() || target<=0) {
  4. if(target==0) {
  5. res.push_back(cur);
  6. }
  7. return;
  8. }
  9. for(int i=start;i<candidates.size();i++) {
  10. if(i>start && candidates[i]==candidates[i-1]) continue;
  11. cur.push_back(candidates[i]);
  12. combinationsSumHelper(candidates,target-candidates[i],cur,i);
  13. cur.pop_back();
  14. }
  15. }
  16. vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
  17. int vsz = candidates.size();
  18. if(vsz==0) return res;
  19. sort(candidates.begin(),candidates.end());
  20. vector<int> cur;
  21. combinationsSumHelper(candidates,target,cur,0);
  22. return res;
  23. }
posted @ 2014-07-24 11:03  purejade  阅读(73)  评论(0)    收藏  举报