• 39. 组合总和


    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

    candidates 中的数字可以无限制重复被选取。

    说明:

    所有数字(包括 target)都是正整数。
    解集不能包含重复的组合。 
    示例 1:

    输入: candidates = [2,3,6,7], target = 7,
    所求解集为:
    [
    [7],
    [2,2,3]
    ]
    示例 2:

    输入: candidates = [2,3,5], target = 8,
    所求解集为:
    [
      [2,2,2,2],
      [2,3,3],
      [3,5]
    ]

    public class L39 {
    //这是回溯法
    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> result = new ArrayList<>();
    Stack<Integer> stack = new Stack<>();
    getList(candidates,0,target,stack,result);
    return result;

    }
    public static void getList(int[] candisates, int index, int target, Stack<Integer> stack, List<List<Integer>> comb){
    //判断遍历终止的代码
    if(target == 0){
    Stack<Integer> stack02 = new Stack<>();
    stack.forEach(s->stack02.push(s));
    comb.add(stack02);
    return;
    }else if(target<0){
    return;
    }
    //进行遍历
    for(int in = index;in < candisates.length && (target > candisates[in]);in ++){
    stack.push(candisates[in]);
    getList(candisates,in,target - candisates[in],stack,comb);
    stack.pop();
    }
    }

    public static void main(String[] args) {
    int[] can = {3,2,6,7,1};
    Arrays.sort(can);
    List<List<Integer>> result = combinationSum(can,7);
    }
    }
  • 相关阅读:
    Linux中/etc目录下passwd和shadow文件
    Linux基本命令
    Linux目录结构说明与基本操作
    如何用虚拟机VMware Workstation安装CentOs-7
    VPP源码分析及流程图
    VPP环境搭建及配置
    【转】智能指针的交叉引用问题及解决方法
    二叉树的前 中 后 层序遍历
    排序算法
    C和C++的一些区别
  • 原文地址:https://www.cnblogs.com/mayang2465/p/11854715.html
Copyright © 2020-2023  润新知