Skip to content

Commit 1735c26

Browse files
committed
回溯
1 parent 560a76b commit 1735c26

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

17.电话号码的字母组合.go

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* @lc app=leetcode.cn id=17 lang=golang
3+
*
4+
* [17] 电话号码的字母组合
5+
*/
6+
7+
// @lc code=start
8+
func letterCombinations(digits string) []string {
9+
if len(digits) == 0 {
10+
return nil
11+
}
12+
n2m := []string{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}
13+
result := []string{""}
14+
for i:=0; i<len(digits); i++ {
15+
resultL := len(result)
16+
for j := 0; j<resultL; j++ {
17+
s := result[j]
18+
for k, c := range n2m[digits[i]-'2'] {
19+
v := s + string(c)
20+
if k == 0 {
21+
result[j] = v
22+
} else {
23+
result = append(result, v)
24+
}
25+
}
26+
}
27+
}
28+
return result
29+
}
30+
// @lc code=end
31+

39.组合总和.go

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
* @lc app=leetcode.cn id=39 lang=golang
3+
*
4+
* [39] 组合总和
5+
*/
6+
7+
// @lc code=start
8+
func combinationSum(candidates []int, target int) [][]int {
9+
sort.Ints(candidates)
10+
result := make([][]int, 0)
11+
list := make([]int, 0)
12+
backtrack(candidates, list, target, 0, &result)
13+
return result
14+
}
15+
16+
func backtrack(candidates, list []int, target, pos int,result *[][]int) {
17+
if target == 0 {
18+
tmp := make([]int, len(list))
19+
copy(tmp, list)
20+
*result = append(*result, tmp)
21+
}
22+
for i := pos; i < len(candidates); i++ {
23+
v := candidates[i]
24+
if target < v {
25+
break
26+
}
27+
backtrack(candidates, append(list, v), target-v, i, result)
28+
}
29+
}
30+
31+
// @lc code=end
32+

0 commit comments

Comments
 (0)