題目:
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.
2,3,6,7
and target 7
, A solution set is:
[7]
[2, 2, 3]
題解:
還是老問題,用DFS找解決方案,不同點是,這道題: The same repeated number may be chosen from C unlimited number of times.
所以,每次跳進遞迴不用都往後挪一個,還可以利用當前的元素嘗試。
同時,這道題還要判斷重複解。用我之前介紹的兩個方法:
1. if(i>0 && candidates[i] == candidates[i-1])//deal with dupicate
continue;
2. if(!res.contains(item))
res.add(new ArrayList<Integer>(item));
這兩個方法解決。
程式碼如下:
1 public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
3 ArrayList<Integer> item = new ArrayList<Integer>();
4 if(candidates == null || candidates.length==0)
5 return res;
6
7 Arrays.sort(candidates);
8 helper(candidates,target, 0, item ,res);
9 return res;
10 }
11
12 private void helper(int[] candidates, int target, int start, ArrayList<Integer> item,
13 ArrayList<ArrayList<Integer>> res){
14 if(target<0)
15 return;
16 if(target==0){
17 res.add(new ArrayList<Integer>(item));
18 return;
19 }
20
21 for(int i=start;i<candidates.length;i++){
22 if(i>0 && candidates[i] == candidates[i-1])//deal with dupicate
23 continue;
24 item.add(candidates[i]);
25 int newtarget = target - candidates[i];
26 helper(candidates,newtarget,i,item,res);//之所以不傳i+1的原因是:
27 //The same repeated number may be
28 //chosen from C unlimited number of times.
29 item.remove(item.size()-1);
30 }
31 }
2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
3 ArrayList<Integer> item = new ArrayList<Integer>();
4 if(candidates == null || candidates.length==0)
5 return res;
6
7 Arrays.sort(candidates);
8 helper(candidates,target, 0, item ,res);
9 return res;
10 }
11
12 private void helper(int[] candidates, int target, int start, ArrayList<Integer> item,
13 ArrayList<ArrayList<Integer>> res){
14 if(target<0)
15 return;
16 if(target==0){
17 res.add(new ArrayList<Integer>(item));
18 return;
19 }
20
21 for(int i=start;i<candidates.length;i++){
22 if(i>0 && candidates[i] == candidates[i-1])//deal with dupicate
23 continue;
24 item.add(candidates[i]);
25 int newtarget = target - candidates[i];
26 helper(candidates,newtarget,i,item,res);//之所以不傳i+1的原因是:
27 //The same repeated number may be
28 //chosen from C unlimited number of times.
29 item.remove(item.size()-1);
30 }
31 }