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

【分析】

1.与题一思路类似,只是在递归处参数改动

【算法实现】

//v1
public class Solution {
    List<List<Integer>> res;
    List<Integer> temp;
    public List<List<Integer>> combinationSum2(int[] num, int target) {
        res=new ArrayList<List<Integer>>();
        temp=new ArrayList<Integer>();
        Arrays.sort(num);
        getCombination(num,target,0,0);       
        HashSet h = new HashSet(res);     //去除重复的list
        res.clear();
        res.addAll(h);
        return res;
    }
    
    public void getCombination(int[] num,int target,int sum,int level) {
        if(sum==target) {
            res.add(new ArrayList<Integer>(temp));
            return;
        }
        if(sum>target||level==num.length)
            return;
        for(int i=level;i<num.length;i++) {
            sum+=num[i];
            temp.add(num[i]);
            getCombination(num,target,sum,i+1);
            temp.remove(temp.size()-1);
            sum-=num[i];
        }
    }
}
//v2
public
class Solution { List<List<Integer>> result; List<Integer> solu; public List<List<Integer>> combinationSum2(int[] num, int target) { result = new ArrayList<>(); solu = new ArrayList<>(); Arrays.sort(num); getComboSum(num, target, 0, 0); return result; } public void getComboSum(int []num, int target, int sum, int level){ if(sum==target){ result.add(new ArrayList<>(solu)); return; } if(sum>target) return; for(int i=level;i<num.length;i++){ sum+=num[i]; solu.add(num[i]); getComboSum(num, target, sum, i+1); sum-=num[i]; solu.remove(solu.size()-1); while(i<num.length-1 && num[i]==num[i+1]) i++; //比较合适的做法 } } }

 

posted @ 2015-04-21 16:59  hwu_harry  阅读(93)  评论(0编辑  收藏  举报