Skip to content

Commit ba683dd

Browse files
authored
feat: add rust solution to lc problem: No.0046 (#1373)
1 parent c3efaf8 commit ba683dd

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

solution/0000-0099/0046.Permutations/README.md

+34
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,40 @@ impl Solution {
315315
}
316316
```
317317

318+
```rust
319+
impl Solution {
320+
#[allow(dead_code)]
321+
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
322+
let mut ret = Vec::new();
323+
let mut cur_vec = Vec::new();
324+
let mut vis = vec![false; nums.len() + 1];
325+
Self::dfs(&nums, &mut vis, 0, &mut cur_vec, &mut ret);
326+
ret
327+
}
328+
329+
#[allow(dead_code)]
330+
fn dfs(nums: &Vec<i32>, vis: &mut Vec<bool>, index: i32, cur_vec: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
331+
let n = nums.len();
332+
if index as usize == n {
333+
ans.push(cur_vec.clone());
334+
return;
335+
}
336+
// Otherwise, let's iterate the nums vector
337+
for i in 0..n {
338+
if !vis[i] {
339+
// If this number hasn't been visited, then visit it
340+
vis[i] = true;
341+
cur_vec.push(nums[i]);
342+
Self::dfs(nums, vis, index + 1, cur_vec, ans);
343+
// Reset the changes
344+
cur_vec.pop().unwrap();
345+
vis[i] = false;
346+
}
347+
}
348+
}
349+
}
350+
```
351+
318352
### **...**
319353

320354
```

solution/0000-0099/0046.Permutations/README_EN.md

+34
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,40 @@ impl Solution {
286286
}
287287
```
288288

289+
```rust
290+
impl Solution {
291+
#[allow(dead_code)]
292+
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
293+
let mut ret = Vec::new();
294+
let mut cur_vec = Vec::new();
295+
let mut vis = vec![false; nums.len() + 1];
296+
Self::dfs(&nums, &mut vis, 0, &mut cur_vec, &mut ret);
297+
ret
298+
}
299+
300+
#[allow(dead_code)]
301+
fn dfs(nums: &Vec<i32>, vis: &mut Vec<bool>, index: i32, cur_vec: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
302+
let n = nums.len();
303+
if index as usize == n {
304+
ans.push(cur_vec.clone());
305+
return;
306+
}
307+
// Otherwise, let's iterate the nums vector
308+
for i in 0..n {
309+
if !vis[i] {
310+
// If this number hasn't been visited, then visit it
311+
vis[i] = true;
312+
cur_vec.push(nums[i]);
313+
Self::dfs(nums, vis, index + 1, cur_vec, ans);
314+
// Reset the changes
315+
cur_vec.pop().unwrap();
316+
vis[i] = false;
317+
}
318+
}
319+
}
320+
}
321+
```
322+
289323
### **...**
290324

291325
```

0 commit comments

Comments
 (0)