Combination Sum II leetcode java

愛做飯的小瑩子發表於2014-08-02

題目

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]

[1, 1, 6]

 

題解

這道題跟combination sum本質的差別就是當前已經遍歷過的元素只能出現一次。

所以需要給每個candidate一個visited域,來標識是否已經visited了。

當回退的時候,記得要把visited一起也回退了。

程式碼如下:

 1     public static 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         boolean [] visited = new boolean[candidates.length];
 9         helper(candidates,target, 0, item ,res, visited);  
10         return res;  
11     }  
12     
13     private static void helper(int[] candidates, int target, int start, ArrayList<Integer> item,   
14     ArrayList<ArrayList<Integer>> res, boolean[] visited){  
15         if(target<0)  
16             return;  
17         if(target==0){  
18             res.add(new ArrayList<Integer>(item));  
19             return;  
20         }
21         
22         for(int i=start;i<candidates.length;i++){
23             if(!visited[i]){
24                 if(i>0 && candidates[i] == candidates[i-1] && visited[i-1]==false)//deal with dupicate
25                     continue;  
26                 item.add(candidates[i]);
27                 visited[i]=true;
28                 int newtarget = target - candidates[i];
29                 helper(candidates,newtarget,i+1,item,res,visited);  
30                 visited[i]=false;
31                 item.remove(item.size()-1);  
32             }
33         }  
34     } 

 

相關文章