39. Combination Sum java solutions

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

 

 1 public class Solution {
 2     public List<List<Integer>> ans = new ArrayList<List<Integer>>();
 3     public List<List<Integer>> combinationSum(int[] candidates, int target) {
 4         List<Integer> list = new ArrayList<Integer>();
 5         combination(list,candidates,target,0,0);
 6         return ans;
 7     }
 8     
 9     public void combination(List<Integer> list, int[] can, int target, int sum, int s){
10         if(sum == target){
11             List<Integer> tmp = new ArrayList<Integer>(list);
12             ans.add(tmp);
13             return;
14         }
15         if(sum > target) return;
16         for(int i = s; i < can.length; i++){
17             list.add(can[i]);
18             combination(list,can,target,sum+can[i],i);
19             list.remove(list.size()-1);
20         }
21     }
22 }

都是套路。 N queen 问题掌握了就OK

posted @ 2016-07-13 20:30  Miller1991  阅读(151)  评论(0编辑  收藏  举报