46. Permutations

Given a collection of distinct 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].

【思路】求给定向量数组所有元素的全排列问题。

n 个元素有 n! 种全排列,而STL底层文件< algorithm >中有关于排列元素的标准算法:

  1. bool next_permutation(BidirectionalIterator beg , BidirectionalIterator end); 
    该函数会改变区间[beg , end)内的元素次序,使它们符合“下一个排列次序”
  2. bool prev_permutation(BidirectionalIterator beg , BidirectionalIterator end); 
    该函数会改变区间[beg , end)内的元素次序,使它们符合“上一个排列次序”
class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> re;
        if(nums.size()==0) return re;
        sort(nums.begin(), nums.end());
        re.push_back(nums);
        while(next_permutation(nums.begin(),nums.end()))
        {
            re.push_back(nums);
        }
        return re;
    }
};


你可能感兴趣的:(46. Permutations)