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

 

Solution:

 1 public class Solution {
 2     public List<List<Integer>> combinationSum(int[] candidates, int target) {
 3         List<List<Integer>> result=new ArrayList<List<Integer>>();
 4         List<Integer> al=new ArrayList<Integer>();
 5         Arrays.sort(candidates);
 6         dfs(result,al,target,candidates,0);
 7         return result;
 8     }
 9 
10     private void dfs(List<List<Integer>> result, List<Integer> al, int target, int[] candidates, int position) {
11         // TODO Auto-generated method stub
12         if(target<0)
13             return;
14         if(target==0){
15             result.add(new ArrayList<Integer>(al));
16             return;
17         }
18         for(int i=position;i<candidates.length;++i){
19             al.add(candidates[i]);
20             dfs(result, al, target-candidates[i], candidates, i);
21             al.remove(al.size()-1);
22         }    
23     }
24 }

 

注意:

这里在循环的dfs前al里加了candidates[i],在dfs出来后,得remove掉,但是注意啊注意,这里得依次删掉最后一个元素。

dfs中的参数position是i,不能继续用position了!!

posted @ 2014-11-13 02:14  Phoebe815  阅读(156)  评论(0编辑  收藏  举报