39
39
40
40
可以使用map或者定义一个二位数组,例如:string letterMap[ 10] ,来做映射,我这里定义一个二维数组,代码如下:
41
41
42
- ```
42
+ ``` cpp
43
43
const string letterMap[10 ] = {
44
44
"", // 0
45
45
"", // 1
@@ -79,7 +79,7 @@ const string letterMap[10] = {
79
79
80
80
代码如下:
81
81
82
- ```
82
+ ``` cpp
83
83
vector<string> result;
84
84
string s;
85
85
void backtracking (const string& digits, int index)
@@ -95,7 +95,7 @@ void backtracking(const string& digits, int index)
95
95
96
96
代码如下:
97
97
98
- ```
98
+ ```cpp
99
99
if (index == digits.size()) {
100
100
result.push_back(s);
101
101
return;
@@ -281,7 +281,7 @@ class Solution {
281
281
282
282
## Python
283
283
** 回溯**
284
- ``` python3
284
+ ``` python
285
285
class Solution :
286
286
def __init__ (self ):
287
287
self .answers: List[str ] = []
@@ -317,7 +317,7 @@ class Solution:
317
317
self .answer = self .answer[:- 1 ] # 回溯
318
318
```
319
319
** 回溯简化**
320
- ``` python3
320
+ ``` python
321
321
class Solution :
322
322
def __init__ (self ):
323
323
self .answers: List[str ] = []
@@ -420,7 +420,8 @@ var letterCombinations = function(digits) {
420
420
};
421
421
```
422
422
423
- C:
423
+ ## C
424
+
424
425
``` c
425
426
char * path;
426
427
int pathTop;
@@ -481,6 +482,47 @@ char ** letterCombinations(char * digits, int* returnSize){
481
482
}
482
483
```
483
484
485
+ ## Swift
486
+
487
+ ```swift
488
+ func letterCombinations(_ digits: String) -> [String] {
489
+ // 按键与字母串映射
490
+ let letterMap = [
491
+ "",
492
+ "", "abc", "def",
493
+ "ghi", "jkl", "mno",
494
+ "pqrs", "tuv", "wxyz"
495
+ ]
496
+ // 把输入的按键字符串转成Int数组
497
+ let baseCode = ("0" as Character).asciiValue!
498
+ let digits = digits.map { c in
499
+ guard let code = c.asciiValue else { return -1 }
500
+ return Int(code - baseCode)
501
+ }.filter { $0 >= 0 && $0 <= 9 }
502
+ guard !digits.isEmpty else { return [] }
503
+
504
+ var result = [String]()
505
+ var s = ""
506
+ func backtracking(index: Int) {
507
+ // 结束条件:收集结果
508
+ if index == digits.count {
509
+ result.append(s)
510
+ return
511
+ }
512
+
513
+ // 遍历当前按键对应的字母串
514
+ let letters = letterMap[digits[index]]
515
+ for letter in letters {
516
+ s.append(letter) // 处理
517
+ backtracking(index: index + 1) // 递归,记得+1
518
+ s.removeLast() // 回溯
519
+ }
520
+ }
521
+ backtracking(index: 0)
522
+ return result
523
+ }
524
+ ```
525
+
484
526
485
527
-----------------------
486
528
<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
0 commit comments