本文主要是介绍Leetcode Day21组合总和,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
39 元素可重复选
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
可以重复选, 代表for j in range(start, n)
中, 下一个dfs起点可以是j, 这样代表了重复选择, 但是如何保证不会死循环呢, 就需要利用都是正数的条件了
class Solution:def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:ans = []def dfs(path, partial_sum, start):if partial_sum > target:returnif partial_sum == target:ans.append(path[:])return for j in range(start, len(candidates)):path.append(candidates[j])dfs(path, partial_sum + candidates[j], j)path.pop()dfs([], 0, 0)return ans
39 nums中有重复, 但每个只能选一次
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
只用添加两个改变, 横向去重和下一个的开始index会变为j + 1
class Solution:def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:ans = []candidates.sort()def dfs(path, partial_sum, start):if partial_sum > target:returnif partial_sum == target:ans.append(path[:])returnfor j in range(start, len(candidates)):if j > start and candidates[j] == candidates[j - 1]:continuepath.append(candidates[j])dfs(path, partial_sum + candidates[j], j + 1)path.pop()dfs([], 0, 0)return ans
377
输入:nums = [1,2,3], target = 4
输出:7
解释:
所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
class Solution:def combinationSum4(self, nums: List[int], target: int) -> int:dp = [1] + [0] * targetfor i in range(1, len(dp)):for num in nums:if num > target:continuedp[i] += dp[i - num]return dp[-1]
这篇关于Leetcode Day21组合总和的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!