mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 回溯算法去重问题的另一种写法.md
This commit is contained in:
@ -604,6 +604,44 @@ impl Solution {
|
||||
}
|
||||
```
|
||||
|
||||
**47. 全排列 II**
|
||||
|
||||
```rust
|
||||
use std::collections::HashSet;
|
||||
impl Solution {
|
||||
pub fn permute_unique(mut nums: Vec<i32>) -> Vec<Vec<i32>> {
|
||||
let mut res = vec![];
|
||||
let mut path = vec![];
|
||||
let mut used = vec![false; nums.len()];
|
||||
Self::backtracking(&mut res, &mut path, &nums, &mut used);
|
||||
res
|
||||
}
|
||||
pub fn backtracking(
|
||||
res: &mut Vec<Vec<i32>>,
|
||||
path: &mut Vec<i32>,
|
||||
nums: &Vec<i32>,
|
||||
used: &mut Vec<bool>,
|
||||
) {
|
||||
if path.len() == nums.len() {
|
||||
res.push(path.clone());
|
||||
return;
|
||||
}
|
||||
let mut helper_set = HashSet::new();
|
||||
for i in 0..nums.len() {
|
||||
if used[i] || helper_set.contains(&nums[i]) {
|
||||
continue;
|
||||
}
|
||||
helper_set.insert(nums[i]);
|
||||
path.push(nums[i]);
|
||||
used[i] = true;
|
||||
Self::backtracking(res, path, nums, used);
|
||||
used[i] = false;
|
||||
path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
|
Reference in New Issue
Block a user