File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
0017 Letter Combinations of a Phone Number Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 0017. Letter Combinations of a Phone Number
2
+
3
+ * Difficulty: medium
4
+ * Link: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
5
+ * Topics: Backtracking
6
+
7
+ # Clarification
8
+
9
+ 1 . Check the inputs and outputs
10
+ - INPUT: string
11
+ - OUTPUT: List[ String]
12
+
13
+ # Naive Solution
14
+
15
+ ### Thought Process
16
+
17
+ - 建立數字對應的 map
18
+ - Backtracking
19
+ - 停止條件
20
+ - len(substring) == len(inputstring)
21
+ - 非停止條件
22
+ - forloop
23
+ - 對每個letter backtrack
24
+ - Implement
25
+
26
+ ``` python
27
+ class Solution :
28
+ def letterCombinations (self , digits : str ) -> List[str ]:
29
+ digit_map = {
30
+ " 2" : " abc" ,
31
+ " 3" :" def" ,
32
+ " 4" :" ghi" ,
33
+ " 5" :" jkl" ,
34
+ " 6" :" mno" ,
35
+ " 7" :" pqrs" ,
36
+ " 8" :" tuv" ,
37
+ " 9" :" wxyz"
38
+ }
39
+ if len (digits) == 0 :
40
+ return []
41
+ chars = list (digits)
42
+ result = []
43
+ def backtrack (substr , res ):
44
+ if len (substr) == len (digits):
45
+ return result.append(substr)
46
+ for i in range (len (res)):
47
+ letters = list (digit_map.get(res[i]))
48
+ for letter in letters:
49
+ backtrack(substr+ letter, res[i+ 1 :])
50
+
51
+ backtrack(" " , chars)
52
+ return result
53
+ ```
54
+
55
+
56
+ # ## Complexity
57
+
58
+ - Time complexity:
59
+ - Space complexity: $ O(N)$
60
+ - N: len (digits)
You can’t perform that action at this time.
0 commit comments