Permutations II

本文提供了一个C++实现的算法,用于生成包含重复元素的集合的所有唯一排列。通过递归调用和巧妙地避免重复交换元素来确保结果中没有重复的排列。

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].

 

Runtime: 28ms

 1 class Solution {
 2 public:
 3     vector<vector<int>> permuteUnique(vector<int>& nums) {
 4         vector<vector<int> > result;
 5         if(nums.empty()) return result;
 6         
 7         helper(result, nums, 0, nums.size() - 1);
 8         return result;
 9     }
10     
11     void helper(vector<vector<int> >& result, vector<int>& nums, int depth, int n){
12         if(depth == n){
13             result.push_back(nums);
14             return;
15         }
16         
17         for(int i = depth; i < nums.size(); i++){
18             if(noSwap(nums, depth, i)) continue;
19             
20             swap(nums[depth], nums[i]);
21             helper(result, nums, depth + 1, n);
22             swap(nums[depth], nums[i]);
23         }
24     }
25     
26     bool noSwap(vector<int>& nums, int depth, int i){
27         for(int j = depth; j < i; j++){
28             if(nums[j] == nums[i])
29                 return true;
30         }
31         return false;
32     }
33 };

 

转载于:https://www.cnblogs.com/amazingzoe/p/4873390.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值