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

在此应注意到candidates中的元素可重复出现,且最后的结果中不应包含重复的组合。使用动态规划的想法来解决这个问题:对应每个target,我们可以选择使用candidates中的第一个元素和不使用第一个元素来拼凑,这种想法覆盖了正面与反面,因此递归求解后的组合是不重不漏的。应注意到,使用第一个元素后,target的值应变为target - candidates[0]AC的代码如下:
class Solution(object):
    def combinationSum(self, candidates, target):
        if not candidates or target <= 0:
            return [[], ]
        res = []
        self.combination_help(candidates, [], target, res)
        return res

    def combination_help(self, candidates, path, remain, res):
        if remain < 0 or not candidates:
            return
        if remain == 0:
            res.append(path)
            return
        self.combination_help(candidates, path + [candidates[0], ], remain - candidates[0], res)
        self.combination_help(candidates[1:], path, remain, res)

查看讨论区的方法可以发现,常应用DFS的方法来解决这个问题。其中关键代码如下:

def dfs(self, nums, target, index, path, res):
    if target < 0:
        return  # backtracking
    if target == 0:
        res.append(path)
        return
    for i in xrange(index, len(nums)):
        self.dfs(nums, target-nums[i], i, path+[nums[i]], res)

可以看到,在for循环中,新调用的dfs函数的index参数仍为i, 而非i + 1,这是因为题目中说明每个元素可以使用多次。

而这种for循环的迭代,和上面自己的这种解法实际上是一样的,都是candidates[0]开始不停迭代使用,去凑齐target

原文地址:https://www.cnblogs.com/plank/p/9104160.html

时间: 2024-10-21 05:48:59

LeetCode39Combination Sum的相关文章

[leetcode-39-Combination Sum]

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (in

Leetcode39---&gt;Combination Sum(在数组中找出和为target的组合)

题目: 给定一个数组candidates和一个目标值target,求出数组中相加结果为target的数字组合: 举例: For example, given candidate set [2, 3, 6, 7] and target 7, A solution set is: [[7],[2, 2, 3]] 从举例中可以看出,同一个数字可以使用多次,且结果是唯一的: 解题思路: 我个人感觉该题目一点也不难,其实也是一个递归的过程,当达到递归条件时,就将结果加入结果集: 首先题目没说给的数组有啥特

LeetCode OJ - Sum Root to Leaf Numbers

这道题也很简单,只要把二叉树按照宽度优先的策略遍历一遍,就可以解决问题,采用递归方法越是简单. 下面是AC代码: 1 /** 2 * Sum Root to Leaf Numbers 3 * 采用递归的方法,宽度遍历 4 */ 5 int result=0; 6 public int sumNumbers(TreeNode root){ 7 8 bFSearch(root,0); 9 return result; 10 } 11 private void bFSearch(TreeNode ro

129. Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T

Leetcode 494 Target Sum 动态规划 背包+滚动数据

这是一道水题,作为没有货的水货楼主如是说. 题意:已知一个数组nums {a1,a2,a3,.....,an}(其中0<ai <=1000(1<=k<=n, n<=20))和一个数S c1a1c2a2c3a3......cnan = S, 其中ci(1<=i<=n)可以在加号和减号之中任选. 求有多少种{c1,c2,c3,...,cn}的排列能使上述等式成立. 例如: 输入:nums is [1, 1, 1, 1, 1], S is 3. 输出 : 5符合要求5种

31.SUM() 函数

SUM() 函数 SUM 函数返回数值列的总数(总额). SQL SUM() 语法 SELECT SUM(column_name) FROM table_name SQL SUM() 实例 我们拥有下面这个 "Orders" 表: O_Id OrderDate OrderPrice Customer 1 2008/12/29 1000 Bush 2 2008/11/23 1600 Carter 3 2008/10/05 700 Bush 4 2008/09/28 300 Bush 5

1305 Pairwise Sum and Divide

基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题 有这样一段程序,fun会对整数数组A进行求值,其中Floor表示向下取整: fun(A) sum = 0 for i = 1 to A.length for j = i+1 to A.length sum = sum + Floor((A[i]+A[j])/(A[i]*A[j])) return sum 给出数组A,由你来计算fun(A)的结果.例如:A = {1, 4, 1},fun(A) = [5/4] + [

Java [Leetcode 303]Range Sum Query - Immutable

题目描述: Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the ar

LeetCode 303. Range Sum Query - Immutable

求数组nums[i,j]的和 思路:另开一sum数组,sum[i]为nums[0,i]的和,所以nums[i,j] = sum[j] - sum[i-1] 1 class NumArray { 2 public: 3 vector<int> sum; 4 NumArray(vector<int> &nums) { 5 sum.resize(nums.size(), 0); 6 sum[0] = nums[0]; 7 int len = nums.size(); 8 for(