Skip to content

Commit 989365f

Browse files
committed
add LeetCode 39. 组合总和
1 parent 77a5a0b commit 989365f

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
给定一个无重复元素的数组 `candidates` 和一个目标数 `target` ,找出 `candidates` 中所有可以使数字和为 `target` 的组合。
6+
7+
`candidates` 中的数字可以无限制重复被选取。
8+
9+
说明:
10+
11+
```javascript
12+
所有数字(包括 target)都是正整数。
13+
解集不能包含重复的组合。
14+
```
15+
16+
示例 1:
17+
18+
```javascript
19+
输入:candidates = [2,3,6,7], target = 7,
20+
所求解集为:
21+
[
22+
[7],
23+
[2,2,3]
24+
]
25+
```
26+
27+
示例 2:
28+
29+
```javascript
30+
输入:candidates = [2,3,5], target = 8,
31+
所求解集为:
32+
[
33+
[2,2,2,2],
34+
[2,3,3],
35+
[3,5]
36+
]
37+
```
38+
39+
40+
41+
提示:
42+
43+
```javascript
44+
1 <= candidates.length <= 30
45+
1 <= candidates[i] <= 200
46+
candidate 中的每个元素都是独一无二的。
47+
1 <= target <= 500
48+
```
49+
50+
来源:力扣(LeetCode)
51+
链接:https://leetcode-cn.com/problems/combination-sum
52+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
53+
54+
55+
56+
## 解题思路
57+
这道题是组合题,但是这道题有意思的是当前元素可以重复无限制选取,那么我们可以改一下另外一道组合题的思路,下一层也从 `i`开始即可,然后本题元素重复,那么我们不需要进行排序然后剪枝了。
58+
59+
```javascript
60+
// 当前元素可以无限制选取,下一层也从i开始取
61+
dfs(t.slice(),i,sum+candidates[i]);
62+
```
63+
64+
![](https://img-blog.csdnimg.cn/20200918165742837.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjQyOTcxOA==,size_16,color_FFFFFF,t_70#pic_center)
65+
<a href="https://leetcode-cn.com/problems/combination-sum/solution/shou-hua-tu-jie-zu-he-zong-he-combination-sum-by-x/">参考xiao_ben_zhu图解</a>
66+
67+
```javascript
68+
var combinationSum = function(candidates, target) {
69+
let res = [];
70+
let dfs = (t,start,sum) => {
71+
if(sum >= target){ // 防止爆掉
72+
if(sum === target){
73+
res.push(t);
74+
}
75+
return;
76+
}
77+
for(let i=start;i<candidates.length;i++){
78+
t.push(candidates[i]);
79+
// 当前元素可以无限制选取,下一层也从i开始取
80+
dfs(t.slice(),i,sum+candidates[i]);
81+
t.pop();
82+
}
83+
}
84+
dfs([],0,0);
85+
return res;
86+
};
87+
```
88+
89+
90+
91+
## 最后
92+
文章产出不易,还望各位小伙伴们支持一波!
93+
94+
往期精选:
95+
96+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
97+
98+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
99+
100+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
101+
102+
```javascript
103+
学如逆水行舟,不进则退
104+
```
105+
106+

0 commit comments

Comments
 (0)