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