Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f56adb7

Browse files
🐱(backtrace): 216. 组合总和 III
1 parent 9cde1f1 commit f56adb7

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

‎docs/algorithm/backtrack/README.md‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,56 @@ class Solution:
8383
track = []
8484
track_back(nums, track)
8585
return ans
86+
```
87+
88+
## 216. 组合总和 III
89+
90+
[原题链接](https://leetcode-cn.com/problems/combination-sum-iii/)
91+
92+
回溯模板:
93+
94+
```
95+
backtracking() {
96+
if (终止条件) {
97+
存放结果;
98+
}
99+
100+
for (选择:选择列表(可以想成树中节点孩子的数量)) {
101+
递归,处理节点;
102+
backtracking();
103+
回溯,撤销处理结果
104+
}
105+
}
106+
```
107+
108+
### 题解
109+
110+
```python
111+
class Solution:
112+
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
113+
ans = []
114+
'''
115+
element: 数组内答案
116+
start: 遍历的开始位置
117+
num: 剩余数字
118+
'''
119+
def dfs(element, start, num):
120+
# 符合条件,加入最终答案,结束递归
121+
if len(element) == k or num < 0:
122+
if len(element) == k and num == 0:
123+
# print(element)
124+
# 深拷贝
125+
ans.append(element[:])
126+
return
127+
128+
for i in range(start, 10):
129+
# 加入当前值
130+
element.append(i)
131+
# 递归
132+
dfs(element, i + 1, num - i)
133+
# 撤销选择,即回溯
134+
element.pop()
135+
136+
dfs([], 1, n)
137+
return ans
86138
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /