- 思路
不知道为啥看不懂递归,但是却很好想到动态规划,利用哈希表储存前面计算过的组合,比目标值小的每一个数字都已经找到组合,这是再遍历candidate里的数时直接找到哈希表下标为[i-j]里的组合
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
dicts = {}
#哈希表
for i in range(1, target+1):
dicts[i] = []
for i in range(1, target+1):
for j in candidates:
if j == i:
dicts[i].append([j])
elif j<i:
for k in dicts[i-j]:
x = k[:]
x.append(j)
x.sort()
if x not in dicts[i]:
dicts[i].append(x)
return dicts[target]