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 77a5a0b

Browse files
add LeetCode 40. 组合总和 II
1 parent c02e94e commit 77a5a0b

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
6+
给定一个数组 `candidates `和一个目标数 target ,找出` candidates` 中所有可以使数字和为` target `的组合。
7+
8+
`candidates `中的每个数字在每个组合中只能使用一次。
9+
10+
说明:
11+
12+
所有数字(包括目标数)都是正整数。
13+
解集不能包含重复的组合。
14+
示例 1:
15+
16+
```javascript
17+
输入: candidates = [10,1,2,7,6,1,5], target = 8,
18+
所求解集为:
19+
[
20+
[1, 7],
21+
[1, 2, 5],
22+
[2, 6],
23+
[1, 1, 6]
24+
]
25+
```
26+
27+
示例 2:
28+
29+
```javascript
30+
输入: candidates = [2,5,2,1,2], target = 5,
31+
所求解集为:
32+
[
33+
[1,2,2],
34+
[5]
35+
]
36+
```
37+
38+
来源:力扣(LeetCode)
39+
链接:https://leetcode-cn.com/problems/combination-sum-ii
40+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
41+
42+
## 解题思路
43+
44+
这道题也是一道组合题,但是这道题数组里面是存在重复元素的,组合题的话,为了更好地去重,我们可以先对数组进行排序,然后对于每一层如果相邻元素相同,就剪掉该分支即可。
45+
![](https://img-blog.csdnimg.cn/20200918163049991.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjQyOTcxOA==,size_16,color_FFFFFF,t_70#pic_center)
46+
<a href="https://leetcode-cn.com/problems/combination-sum-ii/solution/man-tan-wo-li-jie-de-hui-su-chang-wen-shou-hua-tu-/">参考xiao_ben_zhu大佬图解</a>
47+
48+
注意求和那里,如果只判断是否相等的话,可能会出现爆掉情况。
49+
50+
51+
```javascript
52+
var combinationSum2 = function (candidates, target) {
53+
let res = [];
54+
candidates.sort((a, b) => a - b);
55+
let dfs = (t, start, sum) => {
56+
if (sum >= target) { // 加这外层,超出范围了也终止,防爆栈
57+
if (sum === target) {
58+
res.push(t);
59+
}
60+
return;
61+
}
62+
// 组合
63+
for (let i = start; i < candidates.length; i++) {
64+
// 组合元素不能重复,去掉同一层重复的元素
65+
if (i > start && candidates[i] == candidates[i - 1]) continue;
66+
t.push(candidates[i]);
67+
// 组合元素去重,即当前选择和下一层的不能重复
68+
dfs(t.slice(), i + 1, sum + candidates[i]);
69+
t.pop();
70+
}
71+
}
72+
dfs([], 0, 0);
73+
return res;
74+
};
75+
```
76+
77+
78+
79+
80+
## 最后
81+
文章产出不易,还望各位小伙伴们支持一波!
82+
83+
往期精选:
84+
85+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
86+
87+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
88+
89+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
90+
91+
```javascript
92+
学如逆水行舟,不进则退
93+
```
94+
95+

0 commit comments

Comments
(0)

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