mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
@ -271,8 +271,25 @@ class Solution {
|
||||
```
|
||||
|
||||
Python:
|
||||
|
||||
|
||||
```python3
|
||||
class Solution:
|
||||
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
|
||||
res = []
|
||||
path = []
|
||||
def backtrack(candidates,target,sum,startIndex):
|
||||
if sum > target: return
|
||||
if sum == target: return res.append(path[:])
|
||||
for i in range(startIndex,len(candidates)):
|
||||
if sum + candidates[i] >target: return #如果 sum + candidates[i] > target 就终止遍历
|
||||
sum += candidates[i]
|
||||
path.append(candidates[i])
|
||||
backtrack(candidates,target,sum,i) #startIndex = i:表示可以重复读取当前的数
|
||||
sum -= candidates[i] #回溯
|
||||
path.pop() #回溯
|
||||
candidates = sorted(candidates) #需要排序
|
||||
backtrack(candidates,target,0,0)
|
||||
return res
|
||||
```
|
||||
Go:
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user