2015年9月20日星期日

Leetcode 39 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 (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 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3] 
Solution 1: DFS, pay attention to not duplicate.


 public class Solution {  
   public List<List<Integer>> combinationSum(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,target-nums[d],one,res);//use 1 or more  
     one.remove(one.size()-1);  
     dfs(nums,k,target,one,res);//use 0  
   }  
 }  

没有评论:

发表评论