原題鏈接 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;
}
};