leetcode--Combination Sum II

来源:互联网 发布:魔域淘宝绑6星vip 编辑:程序博客网 时间:2024/06/03 22:47

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inC 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]
[java] view plain copy
  1. public class Solution {  
  2.     public List<List<Integer>> combinationSum2(int[] candidates, int target) {  
  3.         List<List<Integer>> res = new ArrayList<List<Integer>>();  
  4.         Arrays.sort(candidates);          
  5.         Stack<Integer> stack = new Stack<Integer>();          
  6.         dfs(res, stack, target, 0, candidates,0);  
  7.         return res;  
  8.     }  
  9.       
  10.     void dfs(List<List<Integer>> res,Stack<Integer> stack,int target,int cur,int[] arr,int sum){        
  11.         if(sum==target){              
  12.             ArrayList<Integer> data = new ArrayList<Integer>(stack);  
  13.             res.add(data);  
  14.             return;  
  15.         }else if(sum>target) return;  
  16.         else{  
  17.             int pre = -1;  
  18.             for(int i=cur;i<arr.length;i++){  
  19.                 if(pre!=arr[i]){//去重  
  20.                     stack.add(arr[i]);  
  21.                     sum += arr[i];  
  22.                     dfs(res, stack, target, i+1, arr,sum);  
  23.                     sum -= arr[i];  
  24.                     stack.pop();  
  25.                     pre = arr[i];  
  26.                 }  
  27.             }  
  28.         }  
  29.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/45725657