添加0017.电话号码的字母组合 Ruby实现

This commit is contained in:
han
2023-08-30 16:28:31 +08:00
parent 5df6ab7bdf
commit 6141fc92bb

View File

@ -694,6 +694,44 @@ object Solution {
} }
``` ```
### Ruby
```ruby
def letter_combinations(digits)
letter_map = {
2 => ['a','b','c'],
3 => ['d','e','f'],
4 => ['g','h','i'],
5 => ['j','k','l'],
6 => ['m','n','o'],
7 => ['p','q','r','s'],
8 => ['t','u','v'],
9 => ['w','x','y','z']
}
result = []
path = []
return result if digits.size == 0
backtracking(result, letter_map, digits.split(''), path, 0)
result
end
def backtracking(result, letter_map, digits, path, index)
if path.size == digits.size
result << path.join('')
return
end
hash[digits[index].to_i].each do |chr|
path << chr
#index + 1代表处理下一个数字
backtracking(result, letter_map, digits, path, index + 1)
#回溯,撤销处理过的数字
path.pop
end
end
```
<p align="center"> <p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">