Skip to content

Commit ffff02a

Browse files
committed
array: 组合
Change-Id: Id29ee259bc9223e2c73dfb2d18dde79dbe089cfa
1 parent 1587b1f commit ffff02a

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

go/leetcode/40.组合总和-ii.go

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
* @lc app=leetcode.cn id=40 lang=golang
3+
*
4+
* [40] 组合总和 II
5+
*
6+
* https://leetcode-cn.com/problems/combination-sum-ii/description/
7+
*
8+
* algorithms
9+
* Medium (55.85%)
10+
* Likes: 109
11+
* Dislikes: 0
12+
* Total Accepted: 15.1K
13+
* Total Submissions: 27K
14+
* Testcase Example: '[10,1,2,7,6,1,5]\n8'
15+
*
16+
* 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
17+
*
18+
* candidates 中的每个数字在每个组合中只能使用一次。
19+
*
20+
* 说明:
21+
*
22+
*
23+
* 所有数字(包括目标数)都是正整数。
24+
* 解集不能包含重复的组合。 
25+
*
26+
*
27+
* 示例 1:
28+
*
29+
* 输入: candidates = [10,1,2,7,6,1,5], target = 8,
30+
* 所求解集为:
31+
* [
32+
* ⁠ [1, 7],
33+
* ⁠ [1, 2, 5],
34+
* ⁠ [2, 6],
35+
* ⁠ [1, 1, 6]
36+
* ]
37+
*
38+
*
39+
* 示例 2:
40+
*
41+
* 输入: candidates = [2,5,2,1,2], target = 5,
42+
* 所求解集为:
43+
* [
44+
* [1,2,2],
45+
* [5]
46+
* ]
47+
*
48+
*/
49+
50+
import (
51+
"sort"
52+
)
53+
54+
func helper(arr []int, target int, start int, out *[]int, res *[][]int) {
55+
if target < 0 {
56+
return
57+
}
58+
if target == 0 {
59+
*res = append(*res, append([]int{}, (*out)...)) // 复制值
60+
return
61+
}
62+
for i := start; i < len(arr); i++ {
63+
if i > start && arr[i] == arr[i-1] {
64+
continue
65+
}
66+
*out = append(*out, arr[i])
67+
helper(arr, target-arr[i], i+1, out, res)
68+
*out = (*out)[:len(*out)-1]
69+
}
70+
}
71+
72+
73+
func combinationSum2(candidates []int, target int) [][]int {
74+
out := []int{}
75+
res := [][]int{}
76+
sort.Ints(candidates)
77+
helper(candidates, target, 0, &out, &res)
78+
return res
79+
}
80+

0 commit comments

Comments
 (0)