码迷,mamicode.com
首页 > 其他好文 > 详细

40. 组合总和 II

时间:2019-11-14 13:42:51      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:相等   遍历   bin   ida   一个   父节点   span   现象   跳过   

题目描述:

给定一个数组 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 static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        getList(candidates,0,target,new Stack<>(),result);
        return result;
    }
    public static void getList(int[] candisates, int index, int target, Stack<Integer> stack, List<List<Integer>> comb){
        //判断遍历终止的代码
        if(target == 0){
            comb.add(new ArrayList<>(stack));
            return;
        }
        //进行遍历
        for(int in = index;in < candisates.length && (target >= candisates[in]);in ++){
            //如果该数据与上一个数据相等就跳过--针对重复现象的解决办法,注意里面用到index,可以防止同样父节点下出现相同的子节点
            if(in > index && candisates[in] == candisates[in-1]){
                continue;
            }
            stack.push(candisates[in]);
            getList(candisates,in+1,target - candisates[in],stack,comb);
            stack.pop();
        }
    }
}

 

40. 组合总和 II

标签:相等   遍历   bin   ida   一个   父节点   span   现象   跳过   

原文地址:https://www.cnblogs.com/mayang2465/p/11856503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!