diff --git a/src/problem/mod.rs b/src/problem/mod.rs index b9a2f30..92659b1 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -164,4 +164,5 @@ mod p433_minimum_genetic_mutation; mod p127_word_ladder; mod p208_implement_trie_prefix_tree; mod p211_design_add_and_search_words_data_structure; -mod p212_word_search_ii; \ No newline at end of file +mod p212_word_search_ii; +mod p17_letter_combinations_of_a_phone_number; \ No newline at end of file diff --git a/src/problem/p17_letter_combinations_of_a_phone_number.rs b/src/problem/p17_letter_combinations_of_a_phone_number.rs new file mode 100644 index 0000000..c1874ce --- /dev/null +++ b/src/problem/p17_letter_combinations_of_a_phone_number.rs @@ -0,0 +1,57 @@ +/** + * [17] Letter Combinations of a Phone Number + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn letter_combinations(digits: String) -> Vec { + let mut result = vec![]; + let digits: Vec = digits.chars() + .map(|c| (c.to_digit(10).unwrap() - 2) as usize) + .collect(); + let mut str = Vec::with_capacity(digits.len()); + + Self::search(&digits, &mut str, &mut result, 0); + + result + } + + fn search(digits: &Vec, str: &mut Vec, result: &mut Vec, pos: usize) { + let map = vec![ + vec!['a', 'b', 'c'], + vec!['d', 'e', 'f'], + vec!['g', 'h', 'i'], + vec!['j', 'k', 'l'], + vec!['m', 'n', 'o'], + vec!['p', 'q', 'r', 's'], + vec!['t', 'u', 'v'], + vec!['w', 'x', 'y', 'z'], + ]; + + if pos >= digits.len() { + if !str.is_empty() { + result.push(str.iter().collect()); + } + return; + } + + for &c in &map[digits[pos]] { + str.push(c); + Self::search(digits, str, result, pos + 1); + str.pop(); + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_17() {} +}