【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]);
            }
        }
    }
};

posted @ 2014-12-13 18:23  陆草纯  阅读(2034)  评论(1编辑  收藏  举报