zoukankan      html  css  js  c++  java
  • 【LeetCode】47. Permutations II

    Permutations II

    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].

    首先分析一下与Permutations有何差异。

    记当前位置为start,当前排列数组为cur

    1、cur[start]与cur[start]值相同的元素交换位置会产生大量重复。

    如:1,3,2,1

    两个1互换位置之后,后续的所有排列都是重复的。

    2、cur[start]与其他相同值的元素多次交换位置会产生大量重复。

    如:1,2,3,2

    1与两个2互换位置后,后续的所有排列都是重复的。

    因此改变在于:

    对于同一个值,只交换一次,否则跳过。

    为了保证这一点,必须对cur数组start位置之后的元素排序,这样可以跳过重复元素。

    若不排序会产生如下问题:

    0,0,1,9 --> 9,0,1,0

    0就不连续了,无法进行判断去重,结果又会产生重复。

    class Solution {
    public:
        vector<vector<int> > permuteUnique(vector<int> &num) {
            vector<vector<int> > ret;
            Helper(ret, num, 0);
            return ret;
        }
        void Helper(vector<vector<int> >& ret, vector<int> num, int pos)
        {
            if(pos == num.size()-1)
                ret.push_back(num);
            else
            {
                sort(num.begin()+pos, num.end());
                for(int i = pos; i < num.size(); i ++)
                {
                    if(i != pos && num[i] == num[i-1])
                        continue;
                    swap(num[pos], num[i]);
                    Helper(ret, num, pos+1);
                    swap(num[pos], num[i]);
                }
            }
        }
    };

  • 相关阅读:
    MSBuild、条件编译、预处理命令
    批量数据插入SqlBulkCopy
    WPF 双向绑定
    编程思想之一
    python 提交表单
    python 添加用户
    python 分页
    day9 IO多路复用
    day9 线程、进程和协程深入版
    day8 进程、线程 简介版
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4161693.html
Copyright © 2011-2022 走看看