lintcode:数字组合 II

数字组合 II

给出一组候选数字(C)和目标数字(T),找出C中所有的组合,使组合中数字的和为T。C中每个数字在每个组合中只能使用一次。

 注意事项
  • 所有的数字(包括目标数字)均为正整数。
  • 元素组合(a1, a2, … , ak)必须是非降序(ie, a1 ≤ a2 ≤ … ≤ ak)。
  • 解集不能包含重复的组合。 
样例

给出一个例子,候选数字集合为[10,1,6,7,2,1,5] 和目标数字 8  ,

解集为:[[1,7],[1,2,5],[2,6],[1,1,6]]

解题

和上一题的数字组合很类似,但是这一题是真正的组合问题

还是DFS的思想

public class Solution {
    /**
     * @param num: Given the candidate numbers
     * @param target: Given the target number
     * @return: All the combinations that sum to target
     */
    public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
        // write your code here
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if(num == null || num.length == 0)
            return result;
        Arrays.sort(num);
        ArrayList<Integer> list = new ArrayList<Integer>();
        int start =0;
        DFS(num,target,list,start,result);
        return result;
    }
    public void DFS(int[] num,int target,ArrayList<Integer> list,int start,ArrayList<ArrayList<Integer>> result){
        if( target == 0){
            ArrayList<Integer> tmp = new ArrayList<Integer>(list);// 新建list 才可以
            if(!result.contains(tmp))
                result.add(tmp);
            return;
        }
        for(int i = start;i<num.length;i++){
            if( target < num[i]) // 排序后第一个不成立后面都不成立了
                return;
            target -= num[i];//更新target 和list 
            list.add(num[i]);
            DFS(num,target,list,i+1,result); // 不能重复要从下一个开始
            target +=num[i];// 还原
            list.remove(list.size() - 1);
        }
        
    }
    
}
原文地址:https://www.cnblogs.com/bbbblog/p/5349322.html