File tree 2 files changed +42
-0
lines changed
2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change 32
32
| 34| [ 在排序数组中查找元素的第一个和最后一个位置] ( https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/ ) | [ JavaScript] ( ./algorithms/find-first-and-last-position-of-element-in-sorted-array.js ) | Medium|
33
33
| 35| [ 搜索插入位置] ( https://leetcode.cn/problems/search-insert-position/ ) | [ JavaScript] ( ./algorithms/search-insert-position.js ) | Easy|
34
34
| 39| [ 组合总和] ( https://leetcode.cn/problems/combination-sum/ ) | [ JavaScript] ( ./algorithms/combination-sum.js ) | Medium|
35
+ | 40| [ 组合总和 II] ( https://leetcode.cn/problems/combination-sum-ii/ ) | [ JavaScript] ( ./algorithms/combination-sum-ii.js ) | Medium|
35
36
| 48| [ 旋转图像] ( https://leetcode.cn/problems/rotate-image/ ) | [ JavaScript] ( ./algorithms/rotate-image.js ) | Medium|
36
37
| 49| [ 字母异位词分组] ( https://leetcode.cn/problems/group-anagrams/ ) | [ JavaScript] ( ./algorithms/group-anagrams.js ) | Medium|
37
38
| 54| [ 螺旋矩阵] ( https://leetcode.cn/problems/spiral-matrix/ ) | [ JavaScript] ( ./algorithms/spiral-matrix.js ) | Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 40. 组合总和 II
3
+ * @param {number[] } candidates
4
+ * @param {number } target
5
+ * @return {number[][] }
6
+ */
7
+ var combinationSum2 = function ( candidates , target ) {
8
+ candidates . sort ( ( a , b ) => a - b ) ;
9
+
10
+ const result = [ ] ;
11
+ const path = [ ] ;
12
+ let sum = 0 ;
13
+
14
+ // [1,1,2,5,6,7,10]
15
+
16
+ const backtracking = ( candidates , target , startIndex ) => {
17
+ if ( sum === target ) {
18
+ result . push ( path . slice ( ) ) ;
19
+ return ;
20
+ }
21
+ for (
22
+ let i = startIndex ;
23
+ i < candidates . length && sum + candidates [ i ] <= target ; // 剪枝
24
+ i ++
25
+ ) {
26
+ // 要对同一树层使用过的元素进行跳过
27
+ if ( i > startIndex && candidates [ i ] === candidates [ i - 1 ] ) {
28
+ continue ;
29
+ }
30
+ const curr = candidates [ i ] ;
31
+ path . push ( curr ) ;
32
+ sum += curr ;
33
+ backtracking ( candidates , target , i + 1 ) ;
34
+ sum -= curr ;
35
+ path . pop ( ) ;
36
+ }
37
+ } ;
38
+ backtracking ( candidates , target , 0 ) ;
39
+
40
+ return result ;
41
+ } ;
You can’t perform that action at this time.
0 commit comments