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; } };
原文地址:http://blog.csdn.net/chenlei0630/article/details/42064111