Skip to content

Commit

Permalink
add 46. Permutations
Browse files Browse the repository at this point in the history
  • Loading branch information
stada526 committed May 15, 2024
1 parent 614bdbb commit f1b658e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/solutions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod s_206_reverse_linked_list;
mod s_22_generate_parentheses;
mod s_3_longest_substring_without_repeating_characters;
mod s_424_longest_repeating_character_replacement;
mod s_46_permutations;
mod s_543_diameter_of_binary_tree;
mod s_567_permutation_in_string;
mod s_572_subtree_of_another_tree;
Expand Down
59 changes: 59 additions & 0 deletions src/solutions/s_46_permutations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use std::collections::HashSet;

struct Solution {}

impl Solution {
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut index_set: HashSet<usize> = HashSet::new();
let mut res: Vec<Vec<i32>> = vec![];

for num in 0..nums.len() {
index_set.insert(num);
}

Solution::dfs(&nums, &mut index_set, &mut vec![], &mut res);

return res;
}

fn dfs(
nums: &Vec<i32>,
index_set: &mut HashSet<usize>,
stack: &mut Vec<i32>,
res: &mut Vec<Vec<i32>>,
) {
if index_set.is_empty() {
res.push(stack.clone());
return;
}
for index in index_set.clone().iter() {
stack.push(nums[*index]);
index_set.remove(index);
Solution::dfs(nums, index_set, stack, res);
stack.pop();
index_set.insert(*index);
}
}
}

#[cfg(test)]
mod tests {
use assert_unordered::assert_eq_unordered;

use super::*;

#[test]
fn test() {
let input = vec![1, 2, 3];
let expected = vec![
vec![1, 2, 3],
vec![1, 3, 2],
vec![2, 1, 3],
vec![2, 3, 1],
vec![3, 1, 2],
vec![3, 2, 1],
];
let res = Solution::permute(input);
assert_eq_unordered!(res, expected);
}
}

0 comments on commit f1b658e

Please sign in to comment.