mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
0017.电话号码的字母组合:优化排版,补充Swift版本
This commit is contained in:
@ -39,7 +39,7 @@
|
||||
|
||||
可以使用map或者定义一个二位数组,例如:string letterMap[10],来做映射,我这里定义一个二维数组,代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
const string letterMap[10] = {
|
||||
"", // 0
|
||||
"", // 1
|
||||
@ -79,7 +79,7 @@ const string letterMap[10] = {
|
||||
|
||||
代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
vector<string> result;
|
||||
string s;
|
||||
void backtracking(const string& digits, int index)
|
||||
@ -95,7 +95,7 @@ void backtracking(const string& digits, int index)
|
||||
|
||||
代码如下:
|
||||
|
||||
```
|
||||
```cpp
|
||||
if (index == digits.size()) {
|
||||
result.push_back(s);
|
||||
return;
|
||||
@ -281,7 +281,7 @@ class Solution {
|
||||
|
||||
## Python
|
||||
**回溯**
|
||||
```python3
|
||||
```python
|
||||
class Solution:
|
||||
def __init__(self):
|
||||
self.answers: List[str] = []
|
||||
@ -317,7 +317,7 @@ class Solution:
|
||||
self.answer = self.answer[:-1] # 回溯
|
||||
```
|
||||
**回溯简化**
|
||||
```python3
|
||||
```python
|
||||
class Solution:
|
||||
def __init__(self):
|
||||
self.answers: List[str] = []
|
||||
@ -420,7 +420,8 @@ var letterCombinations = function(digits) {
|
||||
};
|
||||
```
|
||||
|
||||
C:
|
||||
## C
|
||||
|
||||
```c
|
||||
char* path;
|
||||
int pathTop;
|
||||
@ -481,6 +482,47 @@ char ** letterCombinations(char * digits, int* returnSize){
|
||||
}
|
||||
```
|
||||
|
||||
## Swift
|
||||
|
||||
```swift
|
||||
func letterCombinations(_ digits: String) -> [String] {
|
||||
// 按键与字母串映射
|
||||
let letterMap = [
|
||||
"",
|
||||
"", "abc", "def",
|
||||
"ghi", "jkl", "mno",
|
||||
"pqrs", "tuv", "wxyz"
|
||||
]
|
||||
// 把输入的按键字符串转成Int数组
|
||||
let baseCode = ("0" as Character).asciiValue!
|
||||
let digits = digits.map { c in
|
||||
guard let code = c.asciiValue else { return -1 }
|
||||
return Int(code - baseCode)
|
||||
}.filter { $0 >= 0 && $0 <= 9 }
|
||||
guard !digits.isEmpty else { return [] }
|
||||
|
||||
var result = [String]()
|
||||
var s = ""
|
||||
func backtracking(digits: [Int], index: Int) {
|
||||
// 结束条件:收集结果
|
||||
if index == digits.count {
|
||||
result.append(s)
|
||||
return
|
||||
}
|
||||
|
||||
// 遍历当前按键对应的字母串
|
||||
let letters = letterMap[digits[index]]
|
||||
for letter in letters {
|
||||
s.append(letter) // 处理
|
||||
backtracking(digits: digits, index: index + 1) // 递归,记得+1
|
||||
s.removeLast() // 回溯
|
||||
}
|
||||
}
|
||||
backtracking(digits: digits, index: 0)
|
||||
return result
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user