|
1 |
| -use std::collections::HashMap; |
2 |
| - |
3 | 1 | impl Solution {
|
4 |
| - fn dfs( |
5 |
| - i: usize, |
6 |
| - s: &mut String, |
7 |
| - cs: &Vec<char>, |
8 |
| - map: &HashMap<char, String>, |
9 |
| - res: &mut Vec<String>, |
10 |
| - ) { |
11 |
| - if i == cs.len() { |
| 2 | + fn dfs(i: usize, digits: &[u8], map: &Vec<Vec<char>>, s: &mut String, res: &mut Vec<String>) { |
| 3 | + if i == digits.len() { |
12 | 4 | res.push(s.clone());
|
13 | 5 | return;
|
14 | 6 | }
|
15 |
| - for c in map.get(&cs[i]).unwrap().chars() { |
16 |
| - s.push(c); |
17 |
| - Self::dfs(i + 1, s, cs, map, res); |
| 7 | + for c in map[(digits[i] - b'2') as usize].iter() { |
| 8 | + s.push(*c); |
| 9 | + Self::dfs(i + 1, digits, map, s, res); |
18 | 10 | s.pop();
|
19 | 11 | }
|
20 | 12 | }
|
21 | 13 |
|
22 | 14 | pub fn letter_combinations(digits: String) -> Vec<String> {
|
23 |
| - let mut res = vec![]; |
24 | 15 | if digits.is_empty() {
|
25 |
| - return res; |
| 16 | + return Vec::new(); |
26 | 17 | }
|
27 |
| - |
28 |
| - let mut map = HashMap::new(); |
29 |
| - map.insert('2', String::from("abc")); |
30 |
| - map.insert('3', String::from("def")); |
31 |
| - map.insert('4', String::from("ghi")); |
32 |
| - map.insert('5', String::from("jkl")); |
33 |
| - map.insert('6', String::from("mno")); |
34 |
| - map.insert('7', String::from("pqrs")); |
35 |
| - map.insert('8', String::from("tuv")); |
36 |
| - map.insert('9', String::from("wxyz")); |
37 |
| - |
38 |
| - Self::dfs( |
39 |
| - 0, |
40 |
| - &mut String::new(), |
41 |
| - &digits.chars().collect(), |
42 |
| - &map, |
43 |
| - &mut res, |
44 |
| - ); |
| 18 | + let digits = digits.as_bytes(); |
| 19 | + let map = vec![ |
| 20 | + vec!['a', 'b', 'c'], |
| 21 | + vec!['d', 'e', 'f'], |
| 22 | + vec!['g', 'h', 'i'], |
| 23 | + vec!['j', 'k', 'l'], |
| 24 | + vec!['m', 'n', 'o'], |
| 25 | + vec!['p', 'q', 'r', 's'], |
| 26 | + vec!['t', 'u', 'v'], |
| 27 | + vec!['w', 'x', 'y', 'z'], |
| 28 | + ]; |
| 29 | + let mut res = Vec::new(); |
| 30 | + Self::dfs(0, digits, &map, &mut String::new(), &mut res); |
45 | 31 | res
|
46 | 32 | }
|
47 | 33 | }
|
0 commit comments