• [LeetCode] 39. Combination Sum


    Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

    The same repeated number may be chosen from candidates unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    Example 1:

    Input: candidates = [2,3,6,7], target = 7,
    A solution set is:
    [
      [7],
      [2,2,3]
    ]
    

    Example 2:

    Input: candidates = [2,3,5], target = 8,
    A solution set is:
    [
      [2,2,2,2],
      [2,3,3],
      [3,5]
    ]

    组合总和。这个题依然是backtracking系列里面需要背下来的题目。既然是求什么样的组合的sum能等于target,那么helper函数的退出条件就是看看什么样的组合的sum == target。同时,为了剪枝/加速,如果当前的sum大于target,就可以提前终止回溯了。

    注意21行为什么递归到下一层的时候还是从i开始是因为数字可以被重复利用。这个地方跟40题还是有点区别的。

    时间O(2^n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public List<List<Integer>> combinationSum(int[] candidates, int target) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         if (candidates == null || candidates.length == 0) {
     5             return res;
     6         }
     7         helper(res, new ArrayList<>(), candidates, target, 0);
     8         return res;
     9     }
    10 
    11     private void helper(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int start) {
    12         if (target < 0) {
    13             return;
    14         }
    15         if (target == 0) {
    16             res.add(new ArrayList<>(list));
    17             return;
    18         }
    19         for (int i = start; i < candidates.length; i++) {
    20             list.add(candidates[i]);
    21             helper(res, list, candidates, target - candidates[i], i);
    22             list.remove(list.size() - 1);
    23         }
    24     }
    25 }

    LeetCode 题目总结

  • 相关阅读:
    【leetcode】Reverse Nodes in k-Group (hard)☆
    JSP简单练习-包装类综合应用实例
    C++ 学习笔记3,struct长度測试,struct存储时的对齐方式
    rsh 无秘钥登陆配置
    【POJ 3122】 Pie (二分+贪心)
    Boss OpenCart 商城自适应主题模板 ABC-0012-01
    理解C语言中指针的声明以及复杂声明的语法
    JQuery编程demo练习
    Growth: 一个关于怎样成为优秀Web Developer 的 App
    改动select默认样式,兼容IE9
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12996790.html
Copyright © 2020-2023  润新知