原题链接 https://leetcode.com/problems/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]
.
求全排列。
我开始想到了c++算法库中的next_permutation,然后就是了一下 然后就ac了。(ps: 数组要先排序)。
当然也可以使用回溯法解决。
然后我就上网查了一下next_permutation的实现方法。
大家可以去看这个 http://www.cnblogs.com/devymex/archive/2010/08/17/1801122.html
还有一种方法就是使用逆康托展开,直接算出来。
我就偷懒不叙述了。
class Solution {
public:
vector<vector<int> > permute(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int> >ans;
ans.push_back(nums);
while (next_permutation(nums.begin(), nums.end()))
ans.push_back(nums);
return ans;
}
};