• 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 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();
            }
        }
    }
  • 相关阅读:
    mysql存储过程分库分表
    上取整与下取整的转换
    《windows内核安全与驱动开发》ctrl2cap中的ObReferenceObjectByName疑问
    JavaScript基础入门教程(六)
    Unicode中的BOM
    JavaScript基础入门教程(五)
    JavaScript基础入门教程(四)
    JavaScript基础入门教程(三)
    JavaScript基础入门教程(一)
    web及网络基础
  • 原文地址:https://www.cnblogs.com/mayang2465/p/11856503.html
Copyright © 2020-2023  润新知