Skip to content

Commit 74ec694

Browse files
committed
add dfs
1 parent 86d9e48 commit 74ec694

File tree

3 files changed

+39
-4
lines changed

3 files changed

+39
-4
lines changed

problems/0017.letter-combinations-of-a-phone-number/README.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
22

3+
34
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
45

6+
<p align="center">
7+
<img src=http://on64lz47x.bkt.clouddn.com/leetcode17.png>
8+
</p>
59

610
Example:
711

@@ -10,4 +14,3 @@ Input: "23"
1014
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
1115
```
1216

13-
>构建map循环

problems/0017.letter-combinations-of-a-phone-number/run.go

+33-2
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
package closest
22

3+
import "fmt"
34

4-
var jp = []string{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
5+
// bfs
56
func letterCombinations(digits string) []string {
7+
var jp = []string{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
68
ld := len(digits)
79
// 初始化
810
r := []string{}
911
if ld == 0 {
1012
return r
1113
}
12-
r=[]string{""}
14+
r = []string{""}
1315
for i := 0; i < ld; i++ {
1416
var tmp []string
1517
// 获取jp对应的下标
@@ -24,3 +26,32 @@ r=[]string{""}
2426
}
2527
return r
2628
}
29+
30+
// dfs
31+
func letterCombinationsDFS(digits string) []string {
32+
var jp = []string{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
33+
cur := make([]rune, len(digits))
34+
ans = dfs(digits, jp, 0, cur)
35+
return ans
36+
}
37+
38+
var (
39+
ans []string
40+
)
41+
42+
func dfs(digits string, jp []string, l int, cur []rune) []string {
43+
44+
if l == len(digits) {
45+
if l > 0 {
46+
ans = append(ans, string(cur))
47+
}
48+
return ans
49+
}
50+
s := jp[digits[l]-'0']
51+
for _, v := range s {
52+
cur[l] = v
53+
fmt.Println("cur:", string(cur))
54+
ans = dfs(digits, jp, l+1, cur)
55+
}
56+
return ans
57+
}

problems/0017.letter-combinations-of-a-phone-number/run_test.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ func TestRun(t *testing.T) {
99

1010
target := "23"
1111

12-
s := letterCombinations(target)
12+
// s := letterCombinations(target)
13+
s := letterCombinationsDFS(target)
1314
fmt.Println(s)
1415
}

0 commit comments

Comments
 (0)