diff --git a/solution/0000-0099/0046.Permutations/README.md b/solution/0000-0099/0046.Permutations/README.md index 62d13ebb831fb..6af8a6d4b4151 100644 --- a/solution/0000-0099/0046.Permutations/README.md +++ b/solution/0000-0099/0046.Permutations/README.md @@ -315,6 +315,40 @@ impl Solution { } ``` +```rust +impl Solution { + #[allow(dead_code)] + pub fn permute(nums: Vec) -> Vec> { + let mut ret = Vec::new(); + let mut cur_vec = Vec::new(); + let mut vis = vec![false; nums.len() + 1]; + Self::dfs(&nums, &mut vis, 0, &mut cur_vec, &mut ret); + ret + } + + #[allow(dead_code)] + fn dfs(nums: &Vec, vis: &mut Vec, index: i32, cur_vec: &mut Vec, ans: &mut Vec>) { + let n = nums.len(); + if index as usize == n { + ans.push(cur_vec.clone()); + return; + } + // Otherwise, let's iterate the nums vector + for i in 0..n { + if !vis[i] { + // If this number hasn't been visited, then visit it + vis[i] = true; + cur_vec.push(nums[i]); + Self::dfs(nums, vis, index + 1, cur_vec, ans); + // Reset the changes + cur_vec.pop().unwrap(); + vis[i] = false; + } + } + } +} +``` + ### **...** ``` diff --git a/solution/0000-0099/0046.Permutations/README_EN.md b/solution/0000-0099/0046.Permutations/README_EN.md index 1d734e40651c0..2665f00e8a346 100644 --- a/solution/0000-0099/0046.Permutations/README_EN.md +++ b/solution/0000-0099/0046.Permutations/README_EN.md @@ -286,6 +286,40 @@ impl Solution { } ``` +```rust +impl Solution { + #[allow(dead_code)] + pub fn permute(nums: Vec) -> Vec> { + let mut ret = Vec::new(); + let mut cur_vec = Vec::new(); + let mut vis = vec![false; nums.len() + 1]; + Self::dfs(&nums, &mut vis, 0, &mut cur_vec, &mut ret); + ret + } + + #[allow(dead_code)] + fn dfs(nums: &Vec, vis: &mut Vec, index: i32, cur_vec: &mut Vec, ans: &mut Vec>) { + let n = nums.len(); + if index as usize == n { + ans.push(cur_vec.clone()); + return; + } + // Otherwise, let's iterate the nums vector + for i in 0..n { + if !vis[i] { + // If this number hasn't been visited, then visit it + vis[i] = true; + cur_vec.push(nums[i]); + Self::dfs(nums, vis, index + 1, cur_vec, ans); + // Reset the changes + cur_vec.pop().unwrap(); + vis[i] = false; + } + } + } +} +``` + ### **...** ```