最近可能要有华为的面试了,开始刷一刷题吧
用到了回溯算法
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
n = len(candidates)
ans = []
def backtrack(i, temp_sum, temp):
if temp_sum > target:
return
if temp_sum == target:
ans.append(temp)
for j in range(i, n):
if temp_sum > target:
break
backtrack(j, temp_sum+candidates[j], temp+[candidates[j]])
backtrack(0,0,[])
return ans