leetcode-47. Permutations II

题目:

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

Example:

Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

题目描述:

输入一个含有重复数字的序列,返回这些数所能排列出的所有不同的序列。
即含重复数字的全排列。

思路:

依次把每个元素到第一位置,然后递归排列剩下的元素。有一步判断有无重复元素,canSwap
用来判断之前重复没重复,重复了就没必要在交换,直接跳过当前元素。
例子:
1.无重复:

输入123
输出123 132 213 231 321 312
for循环是控制当前位和之后每一位交换,首先1开头,递归后面的,2在后面序列里开头,在递归,剩下3,保存123;
然后算出一次结果,由于刚才2开头的for循环没结束,开始交换2和3,得到132;
然后由于1开头的for循环没结束,开始交换12得到213,然后继续得到231,然后返回1开头的for循环,交换13,得到321;
继续得到312.
以上是基本流程。
然后本题目有重复元素。

2.有重复

输入112 得到112,121,211
基本原理同上,只是当保存第一个结果112以后要交换后两位12,得到121,然后返回首位for循环交换11,这个时候判断
元素相同不相同,相同说明没必要交换,因为交换后所有所得序列已经得到了(相当于在之前答案里交换两个一样的数字
,比如112交换成112)。

code:
class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int> >res;
        permute_helper(nums,0,res);
        return res;
    }
    bool canSwap(vector<int> &nums, int begin, int end){
        for(int i = begin; i < end; i++)
            if(nums[i] == nums[end])
                return false;
        return true;
    }
    void permute_helper(vector<int>&nums,int now,vector<vector<int> >&res){
        if(now==nums.size()){
            res.push_back(nums);
            return;
        }
        for(int i=now;i<nums.size();++i){
            if(canSwap(nums,now,i)){//如果
                swap(nums,now,i);
                permute_helper(nums,now+1,res);
                swap(nums,now,i);
            }
        }
    }
    void swap(vector<int>&nums,int i,int j){
        int temp=nums[i];
        nums[i]=nums[j];
        nums[j]=temp;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值