LeetCode(47)Permutations II 题目 分析 AC代码

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

分析

用上一题的代码,完全可以AC,那是因为我们的库函数next_permutation()以及prev_permutation()内置排重的代码。。。
其实,题目考察的实质,是让我们自己实现全排,只不过我偷懒了,直接调用了算法库。。。

AC代码

class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int> > ret;

        if (nums.empty())
            return ret;

        sort(nums.begin(), nums.end());
        ret.push_back(nums);
        while (next_permutation(nums.begin(), nums.end()))
            ret.push_back(nums);

        return ret;
    }
};

GitHub测试程序源码