首页 > 代码库 > 39. Combination Sum

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

本题和Permutations1,2比较类似,不过这里面的回溯法的剪枝函数是target,回溯法的特点是可以解决一个问题的所有解或者任意解,且采用深度优先遍历,用于解决组合数比较大的问题,回溯法
具有约束函数和限界函数两个函数。
下面说一下这个题和之前的permutations1,2区别,之前的1是不存在重复元素的时候,且不会遍历同样的元素。2的问题是有重复的的元素,创建一个数组来记录是否used。本题是函数里面传递一个
cur索引,这样不会回头重新计算。代码如下:
 1 public class Solution {
 2     public List<List<Integer>> combinationSum(int[] candidates, int target) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         Arrays.sort(candidates);
 5         backtracking(res,candidates,target,new ArrayList<Integer>(),0);
 6         return res;
 7     }
 8     public void backtracking(List<List<Integer>> res,int[] candidates,int target,List<Integer> list,int start){
 9         if(target==0){
10             res.add(new ArrayList<Integer>(list));
11         }else{
12             for(int i=start;i<candidates.length;i++){
13                 int sum = target-candidates[i];
14                 if(sum<0) break;
15                 list.add(candidates[i]);
16                 backtracking(res,candidates,sum,list,i);
17                 list.remove(list.size()-1);
18             }
19         }
20     }
21 }

 

39. Combination Sum