|
| 1 | +use std::collections::HashMap; |
| 2 | + |
| 3 | +pub fn phone_keypad_combinations(digits: String) -> Vec<String> { |
| 4 | + if digits.is_empty() { |
| 5 | + return Vec::new(); |
| 6 | + } |
| 7 | + |
| 8 | + let mut keypad_map = HashMap::new(); |
| 9 | + keypad_map.insert('2', "abc"); |
| 10 | + keypad_map.insert('3', "def"); |
| 11 | + keypad_map.insert('4', "ghi"); |
| 12 | + keypad_map.insert('5', "jkl"); |
| 13 | + keypad_map.insert('6', "mno"); |
| 14 | + keypad_map.insert('7', "pqrs"); |
| 15 | + keypad_map.insert('8', "tuv"); |
| 16 | + keypad_map.insert('9', "wxyz"); |
| 17 | + |
| 18 | + let mut result: Vec<String> = Vec::new(); |
| 19 | + let mut curr_combination: Vec<char> = Vec::new(); |
| 20 | + |
| 21 | + let digits_chars: Vec<char> = digits.chars().collect(); |
| 22 | + phone_keypad_combinations_impl(0, &mut curr_combination, &digits_chars, &keypad_map, &mut result); |
| 23 | + |
| 24 | + result |
| 25 | +} |
| 26 | + |
| 27 | +fn phone_keypad_combinations_impl( |
| 28 | + i: usize, |
| 29 | + curr_combination: &mut Vec<char>, |
| 30 | + digits: &Vec<char>, |
| 31 | + keypad_map: &HashMap<char, &str>, |
| 32 | + result: &mut Vec<String> |
| 33 | +) { |
| 34 | + // Termination condition: if all digits have been considered, add the |
| 35 | + // current combination to the output list. |
| 36 | + if curr_combination.len() == digits.len() { |
| 37 | + result.push(curr_combination.iter().collect()); |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + let digit = digits[i]; |
| 42 | + if let Some(letters) = keypad_map.get(&digit) { |
| 43 | + for letter in letters.chars() { |
| 44 | + // Add the current letter. |
| 45 | + curr_combination.push(letter); |
| 46 | + |
| 47 | + // Recursively explore all paths that branch from this combination. |
| 48 | + phone_keypad_combinations_impl(i + 1, curr_combination, digits, keypad_map, result); |
| 49 | + |
| 50 | + // Backtrack by removing the letter we just added. |
| 51 | + curr_combination.pop(); |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments