zoukankan      html  css  js  c++  java
  • leetcode 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]
    ]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/combination-sum
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

     1 public class _39 {
     2 
     3     private void result(int[] candidates, int target, int sum,int cur,List<Integer> subset, List<List<Integer>> res){
     4         if (sum > target)
     5             return ;
     6         if (sum == target){
     7             List<Integer> e = new ArrayList<>();
     8             e.addAll(subset);
     9             res.add(e);
    10             return ;
    11         }
    12         for (int i = cur; i < candidates.length; ++i){
    13             subset.add(candidates[i]);
    14             if (sum + candidates[i] <= target)
    15                 result(candidates, target, sum + candidates[i],i, subset, res);
    16             subset.remove(subset.size()-1);
    17         }
    18 
    19     }
    20 
    21     public List<List<Integer>> combinationSum(int[] candidates, int target) {
    22         List<List<Integer>> res = new ArrayList<>();
    23         List<Integer> subset = new ArrayList<>();
    24 //        Arrays.sort(candidates);
    25         result(candidates,target, 0,0, subset, res);
    26         return res;
    27     }
    28 
    29 
    30     public static void main(String[] args) {
    31         List<List<Integer>> lists = new _39().combinationSum(new int[]{2,3,6,7}, 7);
    32         for (List<Integer> e : lists){
    33             System.out.println(e);
    34         }
    35     }
    36 }
  • 相关阅读:
    Nginx 容器教程
    Docker 微服务教程(搭建真正的网站)
    Docker 微服务教程
    Docker 入门教程
    MacOS Docker 安装
    Mac下Homebrew的安装与使用
    ElasticSearch实战
    使用mac自带终端修改hosts
    菜鸡的Java笔记
    菜鸡的Java笔记 comparator 比较器
  • 原文地址:https://www.cnblogs.com/yfs123456/p/11578006.html
Copyright © 2011-2022 走看看