LeetCode题解:Permutations I and II

Permutations


Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

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

思路:

反复生成permutation即可。生成permutation的思路可以看这里。当然题解里就用std::next_permutation作弊了。

题解:

class Solution {
public:
    vector<vector<int> > permuteUnique(vector<int> &num) {
        vector<vector<int>> ret;
        sort(begin(num), end(num));
        ret.push_back(num);
        while(next_permutation(begin(num), end(num)))
            ret.push_back(num);
        return ret;
    }
};


你可能感兴趣的:(LeetCode)