Skip to content

Commit ea0e12c

Browse files
committed
216
1 parent 56f9920 commit ea0e12c

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,4 +195,5 @@
195195
* [213. House Robber II](leetcode-213-House-RobberII.md)
196196
* [214*. Shortest Palindrome](leetcode-214-Shortest-Palindrome.md)
197197
* [215. Kth Largest Element in an Array](leetcode-215-Kth-Largest-Element-in-an-Array.md)
198+
* [216. Combination Sum III](leetcode-216-Combination-SumIII.md)
198199
* [更多](more.md)

leetcode-201-300.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,6 @@
2828

2929
<a href="leetcode-214-Shortest-Palindrome.html">214. Shortest Palindrome</a>
3030

31-
<a href="leetcode-215-Kth-Largest-Element-in-an-Array.html">215. Kth Largest Element in an Array</a>
31+
<a href="leetcode-215-Kth-Largest-Element-in-an-Array.html">215. Kth Largest Element in an Array</a>
32+
33+
<a href="leetcode-216-Combination-SumIII.html">216. Combination Sum III</a>

leetcode-216-Combination-SumIII.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# 题目描述(中等难度)
2+
3+
![](https://windliang.oss-cn-beijing.aliyuncs.com/216.jpg)
4+
5+
返回所有目标和的组合。`k` 代表每个组合能选取的个数,`n` 代表目标和,可选取的数字是 `1``9`,每种组合中每个数字只能选择一次。
6+
7+
# 思路分析
8+
9+
很典型的回溯法应用了,或者说是 `DFS`。约等于暴力求解,去考虑所有情况,然后依次判断即可。之前也做过很多回溯的题了,这里不细讲了,如果对回溯法不熟悉,大家可以在 [https://leetcode.wang/](https://leetcode.wang/) 左上角搜索「回溯」,多做一些题就有感觉了。
10+
11+
![](https://windliang.oss-cn-beijing.aliyuncs.com/216_2.jpg)
12+
13+
# 解法一 回溯法
14+
15+
回溯法完全可以看做一个模版,整体框架就是一个大的 for 循环,然后先 add,接着利用递归进行遍历,然后再 remove ,继续循环。
16+
17+
```java
18+
public List<List<Integer>> combinationSum3(int k, int n) {
19+
List<List<Integer>> res = new ArrayList<>();
20+
getAnswer(res, new ArrayList<>(), k, n, 1);
21+
return res;
22+
}
23+
24+
private void getAnswer(List<List<Integer>> res, ArrayList<Integer> temp, int k, int n, int start) {
25+
if (temp.size() == k) {
26+
if (n == 0) {
27+
res.add(new ArrayList<>(temp));
28+
}
29+
return;
30+
}
31+
for (int i = start; i < 10; i++) {
32+
temp.add(i);
33+
getAnswer(res, temp, k, n - i, i + 1);
34+
temp.remove(temp.size() - 1);
35+
}
36+
}
37+
```
38+
39+
#
40+
41+
这道题没什么难点,主要就是回溯法的应用。

0 commit comments

Comments
 (0)