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 3a08df6

Browse files
整理
Change-Id: Ieda3f8859b5e795d8ee72c15afb2859ca3344fb6
1 parent ee5b1bd commit 3a08df6

File tree

2 files changed

+37
-22
lines changed

2 files changed

+37
-22
lines changed

‎go/leetcode/77.组合.go

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@
1414
* Testcase Example: '4\n2'
1515
*
1616
* 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
17-
*
17+
*
1818
* 示例:
19-
*
19+
*
2020
* 输入: n = 4, k = 2
2121
* 输出:
2222
* [
@@ -27,27 +27,35 @@
2727
* ⁠ [1,3],
2828
* ⁠ [1,4],
2929
* ]
30-
*
30+
*
3131
*/
3232

3333
// @lc code=start
3434
func combine(n int, k int) [][]int {
35-
out := []int{}
36-
res := [][]int{}
37-
dfs(n, k, &out, &res)
38-
return res
35+
s := &solution{
36+
out: []int{},
37+
res: [][]int{},
38+
}
39+
s.call(n, k)
40+
return s.res
3941
}
4042

41-
func dfs(n int, k int, out *[]int, res *[][]int) {
43+
type solution struct {
44+
out []int
45+
res [][]int
46+
}
47+
48+
func (s *solution) call(n int, k int) {
4249
if k <= 0 {
43-
*res = append(*res, append([]int{}, (*out)...))
50+
s.res = append(s.res, append([]int{}, s.out...))
4451
return
4552
}
4653
for i := n; i >= k; i-- {
47-
*out = append(*out, i)
48-
dfs(i-1, k-1, out, res)
49-
*out = (*out)[:len(*out)-1]
54+
s.out = append(s.out, i)
55+
s.call(i-1, k-1)
56+
s.out = s.out[:len(s.out)-1]
5057
}
5158
}
59+
5260
// @lc code=end
5361

‎go/leetcode/78.子集.go

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,22 +20,29 @@
2020

2121
// 用回溯法,组合模式来做
2222
func subsets(nums []int) [][]int {
23-
result := [][]int{}
24-
path := []int{}
25-
helper(nums, &result, &path, 0)
26-
return result
23+
s := &solution{
24+
res: [][]int{},
25+
path: []int{},
26+
}
27+
s.call(nums, 0)
28+
return s.res
29+
}
30+
31+
type solution struct {
32+
path []int
33+
res [][]int
2734
}
2835

29-
func helper(nums []int, result*[][]int, path*[]int, start int) {
36+
func (s*solution) call(nums[]int, start int) {
3037
if start > len(nums) {
3138
return
3239
}
33-
34-
*result = append(*result, append([]int{}, (*path)...))
40+
41+
s.res = append(s.res, append([]int{}, s.path...))
3542

3643
for i := start; i < len(nums); i++ {
37-
*path = append(*path, nums[i])
38-
helper(nums, result, path, i+1)
39-
*path = (*path)[:len(*path)-1]
44+
s.path = append(s.path, nums[i])
45+
s.call(nums, i+1)
46+
s.path = s.path[:len(s.path)-1]
4047
}
4148
}

0 commit comments

Comments
(0)

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