Permutations II

Q:

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

A:

这次的全排列是在数组中有重复元素的情况下,互换的元素的时候需要记录,如果之前有数字已经互换过,就不要再互换了。ok

class Solution {
public:
    vector<vector<int> > permuteUnique(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return permuteInternal(num, num.size() - 1);
    }
private:
    vector<vector<int> > permuteInternal(vector<int> &num, int end) {
        vector<vector<int> > results;
        vector<int> result;
        if (end < 0) return results;
        if (end == 0) {
            result.push_back(num[end]);
            results.push_back(result);
            return results;
        }
        set<int> swaped_num;
        for (int i = 0; i <= end; ++i) {
            if (swaped_num.find(num[i]) != swaped_num.end()) {
                continue;
            }
            swaped_num.insert(num[i]);
            swap(num[end], num[i]);
            
            vector<vector<int> > part_results = 
                permuteInternal(num, end - 1);
            for (int j = 0; j < part_results.size(); ++j) {
                part_results[j].push_back(num[end]);
                results.push_back(part_results[j]);
            }
            swap(num[end], num[i]);
        }
        return results;
    }
};

 

posted @ 2013-06-16 18:01  dmthinker  阅读(72)  评论(0)    收藏  举报