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 toT.

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, 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] 

思路:和Combination Sum 基本一致,主要不同是不允许一个元素多次被使用。

JAVA代码:

  1. ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer>>();
  2. ArrayList<Integer> cur = new ArrayList<Integer>();
  3. void helper(int[] num,int target,int start) {
  4. if( start==num.length || target<=0) {
  5. if(target==0)
  6. res.add(new ArrayList<Integer>(cur));
  7. return;
  8. }
  9. for(int i=start;i<num.length;i++) {
  10. if(i > start && num[i] == num[i-1]) {
  11. continue;
  12. }
  13. cur.add(num[i]);
  14. helper(num,target-num[i],i+1);
  15. cur.remove(cur.size()-1);
  16. }
  17. }
  18. public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
  19. if(num==null) return res;
  20. Arrays.sort(num);
  21. helper(num,target,0);
  22. return res;
  23. }
posted @ 2014-07-24 11:06  purejade  阅读(68)  评论(0)    收藏  举报