https://leetcode.com/problems/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]
]
我的想法就是coin change的想法,每次金额减去coin币值,在dic里面找amount-coin对应的方法列表,然后每个列表加上当前币值,记得要排序确保唯一性~
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
mem=collections.defaultdict(list)
for i in range(target+1):
for candidate in candidates:
if candidate>i:
continue
elif candidate==i:
mem[i].append([candidate])
elif candidate<i:
tmp=mem[i-candidate]
for tmplist in tmp:
pair=[candidate]+tmplist
if sorted(pair) not in mem[i]:
mem[i].append(sorted(pair))
return mem[target]

本文深入探讨了LeetCode上的组合总和问题,提供了一种基于记忆化的递归解决方案。通过使用候选数字集和目标数,寻找所有可能的组合,使得组合内数字之和等于目标数。文章详细解释了算法思路,包括如何避免重复组合,以及如何利用记忆化减少重复计算。
1599

被折叠的 条评论
为什么被折叠?



