• 0039. Combination Sum (M)


    Combination Sum (M)

    题目

    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]
    ]
    

    题意

    给一串数,找出所有和等于目标值的组合,每个数字可以重复使用。

    思路

    排列组合题很容易想到使用回溯法,但与37. Sudoku Solver不同的是,37只要求在回溯中找到一种符合条件的解即可,而本题需要找到所有符合条件的解,因此这两种回溯法递归函数返回值的含义不同(实际上本题递归函数可以没有返回值,但加上返回值可以在适当的地方直接跳出循环,提高算法的效率)。

    回溯法实现:

    1. 先对数组排序,方便处理。
    2. 递归边界为 sum >= target,其中当 sum == target 时,需要将该解记录下来。
    3. 递归主体:每次加入的值不小于上一次加入的值(因为是递增数列所以很容易处理), 加入后进行递归,递归完成后将加入的数去掉。如果递归返回值为false,说明刚刚加入的数已经使整个序列的和达到了最大限值,不用再继续加入更大的值,可以直接跳出。

    代码实现

    Java

    class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);
            List<List<Integer>> ans = new ArrayList<>();
            solve(candidates, target, 0, new ArrayList<>(), ans, 0);
            return ans;
        }
    
        private boolean solve(int[] candidates, int target, int sum, List<Integer> list, List<List<Integer>> ans, int index) {
            if (sum > target) {
                return false;
            }
            if (sum == target) {
                ans.add(new ArrayList<>(list));
                return false;
            }
    
            for (int i = index; i < candidates.length; i++) {
                list.add(candidates[i]);
                boolean flag = solve(candidates, target, sum + candidates[i], list, ans, i);
                list.remove(list.size() - 1);
                if (!flag) {
                    break;
                }
            }
    
            return true;
        }
    }
    

    JavaScript

    /**
     * @param {number[]} candidates
     * @param {number} target
     * @return {number[][]}
     */
    var combinationSum = function (candidates, target) {
      let res = []
      dfs(candidates, 0, 0, target, [], res)
      return res
    }
    
    let dfs = function (candidates, index, sum, target, list, res) {
      if (index === candidates.length || sum > target) {
        return
      }
    
      if (sum === target) {
        res.push([...list])
        return
      }
    
      list.push(candidates[index])
      dfs(candidates, index, sum + candidates[index], target, list, res)
      list.pop()
      dfs(candidates, index + 1, sum, target, list, res)
    }
    
  • 相关阅读:
    如何自动生成参考文献格式
    VS2010+OpenCV 项目生成EXE文件如何在其他电脑上直接运行
    从多核CPU Cache一致性的应用到分布式系统一致性的概念迁移
    【译】为什么永远都不要使用MongoDB Why You Should Never Use MongoDB
    团队技能提升的二三事儿
    从微信朋友圈的评论可见性,谈因果一致性在分布式系统中的应用
    我所认为的软件可靠性的三重境界
    Redis核心原理与实践--事务实践与源码分析
    Redis核心原理与实践--Redis启动过程源码分析
    选择SaaS平台的那些事
  • 原文地址:https://www.cnblogs.com/mapoos/p/13197113.html
Copyright © 2020-2023  润新知