40.组合总和II

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。

说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。

示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(candidates);
        find(res,list,candidates,target,0);
        return res;
    }    
    
    public void find(List<List<Integer>> res,List<Integer> temp,int[] candidates, int target,int num){
            //递归的终点
            if(target==0){
                res.add(temp);
                return;
            } 
    
            for(int i = num; i < candidates.length && candidates[i] <= target; i++)               {  
                //去重,后面递归那个一定要传i+1,不要写i++
                if(i != num && candidates[i] == candidates[i-1]) {
                    continue;
                }
                List<Integer> list = new ArrayList<>(temp);
                list.add(candidates[i]);
                find(res,list,candidates,target-candidates[i],i+1);
            }   
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。