[Leetcode] Permutations II

来源:互联网 发布:sqlserver 大数据处理 编辑:程序博客网 时间:2024/06/10 21:18

题目:

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


思路:重点在如何避免冗余。比较trivial的一个做法是结果都放到set中,但是需要额外空间。观察题目中的例子可以看出冗余是如何形成的,对于第一个1,和自己swap后的结果为 1 1 2,按照Permuation I的做法,接下来和第二个1 swap,产生冗余结果。再看一个例子:[1, 2, 2]. 当1和第一个2 swap后,结果为 2 1 2,此时1再和后面的2 swap,产生 2 2 1. 但是,在 1 2 2 这步,如果1和第二个2直接swap,产生的结果还是 2 2 1,造成冗余。因此可以看到一个一般情况,对于数组AAAAAABBBBBBCCCCCC,假设当前位置为A,现在开始跟C交换,可以看到:A只需要跟第一个C交换,便可以产生和后面C交换同样的效果。换言之,每次需要交换的,从该元素开始,所有第一次出现的元素。需要注意的是,虽然之前做了排序,但数组在递归的过程中是乱序的,例如CAAAAABBBBBBACCCCC,当前元素为B. 因此不能通过 while (num[i] == num[i+1]) i++; 这样的简单方式判断,因为重复出现的元素可能不连续。


class Solution {public:    void swap(int& a, int& b) {        int temp = a;        a = b;        b = temp;    }        bool can_swap(const vector<int>& num, int start, int end) {   //check duplicates        for (; start < end; ++start) {            if (num[start] == num[end]) return false;        }        return true;    }        void permute_helper(vector<int>& num, int pos, vector<vector<int>>& result) {        if (pos == (int)num.size()) {   //reach the end            result.push_back(num);            return;        }        for (int i = pos; i < (int)num.size(); ++i) {            if (can_swap(num, pos, i)) {                swap(num[pos], num[i]);                permute_helper(num, pos + 1, result);                swap(num[pos], num[i]);            }        }    }        vector<vector<int> > permuteUnique(vector<int> &num) {        sort(num.begin(), num.end());        vector<vector<int>> result;        permute_helper(num, 0, result);        return result;    }};


总结:复杂度为O(n!). 

0 0