问题描述:
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++STL的组合数的性质
代码:
#include <algorithm> //C++
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
int size = num.size();
sort(num.begin(),num.end());
vector<vector<int> > result;
vector<int> first;
for(int i = 0; i <size ; i++){
first.push_back(num[i]);
}
result.push_back(first);
while(next_permutation(num.begin(),num.end())){
vector<int> tmp;
for(int i = 0; i <size ; i++){
tmp.push_back(num[i]);
}
result.push_back(tmp);
}
return result;
}
};