diff --git a/src/problem/mod.rs b/src/problem/mod.rs index b7bcd4e..b35cd27 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -166,4 +166,5 @@ mod p208_implement_trie_prefix_tree; mod p211_design_add_and_search_words_data_structure; mod p212_word_search_ii; mod p17_letter_combinations_of_a_phone_number; -mod p77_combinations; \ No newline at end of file +mod p77_combinations; +mod p46_permutations; \ No newline at end of file diff --git a/src/problem/p46_permutations.rs b/src/problem/p46_permutations.rs new file mode 100644 index 0000000..98716fd --- /dev/null +++ b/src/problem/p46_permutations.rs @@ -0,0 +1,49 @@ +/** + * [46] Permutations + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn permute(nums: Vec) -> Vec> { + let mut result = vec![]; + let mut output = nums.clone(); + + Self::search(output.len(), &mut output, &mut result, 0); + + result + } + + fn search(length: usize, output: &mut Vec, result: &mut Vec>, pos: usize) { + if length == pos { + result.push(output.clone()); + return; + } + + for i in pos..length { + Self::swap(output, i, pos); + Self::search(length, output, result, pos + 1); + Self::swap(output, i, pos); + } + + } + + fn swap(output: &mut Vec, a: usize, b: usize) { + let temp = output[a]; + output[a] = output[b]; + output[b] = temp; + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_46() { + } +}