From 4a203a3787e507cd28016779df9ffbb26e745a8b Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Sun, 5 Mar 2023 11:11:41 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E5=9B=9E=E6=BA=AF=E7=AE=97=E6=B3=95?= =?UTF-8?q?=E5=8E=BB=E9=87=8D=E9=97=AE=E9=A2=98=E7=9A=84=E5=8F=A6=E4=B8=80?= =?UTF-8?q?=E7=A7=8D=E5=86=99=E6=B3=95.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...溯算法去重问题的另一种写法.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/problems/回溯算法去重问题的另一种写法.md b/problems/回溯算法去重问题的另一种写法.md index 08ba64dc..e60bd44a 100644 --- a/problems/回溯算法去重问题的另一种写法.md +++ b/problems/回溯算法去重问题的另一种写法.md @@ -604,6 +604,44 @@ impl Solution { } ``` +**47. 全排列 II** + +```rust +use std::collections::HashSet; +impl Solution { + pub fn permute_unique(mut nums: Vec) -> Vec> { + 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>, + path: &mut Vec, + nums: &Vec, + used: &mut Vec, + ) { + 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(); + } + } +} +``` +