Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add rust solution to lc problem: No.0046 #1373

Merged
merged 2 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions solution/0000-0099/0046.Permutations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,40 @@ impl Solution {
}
```

```rust
impl Solution {
#[allow(dead_code)]
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
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<i32>, vis: &mut Vec<bool>, index: i32, cur_vec: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
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;
}
}
}
}
```

### **...**

```
Expand Down
34 changes: 34 additions & 0 deletions solution/0000-0099/0046.Permutations/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,40 @@ impl Solution {
}
```

```rust
impl Solution {
#[allow(dead_code)]
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
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<i32>, vis: &mut Vec<bool>, index: i32, cur_vec: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
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;
}
}
}
}
```

### **...**

```
Expand Down