2015年9月20日星期日

Leetcode 40 Combination Sum II

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 (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ 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] 

Solution 1: DFS, think about how it different from 39.
 public class Solution {  
   public List<List<Integer>> combinationSum2(int[] candidates, int target) {  
     List<Integer> one=new ArrayList<>();  
     List<List<Integer>> res=new ArrayList<>();  
     Arrays.sort(candidates);  
     dfs(candidates,0,target,one,res);  
     return res;  
   }  
   private void dfs(int[] nums, int d, int target, List<Integer> one, List<List<Integer>> res) {  
     if (target<0) return;  
     if (target==0) {  
       res.add(new ArrayList<Integer>(one));  
       return;  
     }  
     if (d>=nums.length) return;  
     int k=d+1;  
     while (k<nums.length && nums[k]==nums[d]) k++;  
     one.add(nums[d]);  
     dfs(nums,d+1,target-nums[d],one,res);//match 1  
     one.remove(one.size()-1);  
     dfs(nums,k,target,one,res);//match 0  
   }  
 }  

没有评论:

发表评论