2013.12.15 05:08
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]
.
Solution:
The STL library <algorithm> provides a function next_permutation(), which generates the next greater permutation for a sequence. If no greater permutation exists, the smallest permutation will be returned as the result.
I just called next_permutation() for n! times, thus the time complexity is O(n * n!). next_permutation() requires O(n) time on average. Space complexity is O(n).
Accepted code:
1 // 1AC, next_permutation is handy~ 2 #include <algorithm> 3 using namespace std; 4 5 class Solution { 6 public: 7 vector<vector<int> > permute(vector<int> &num) { 8 // IMPORTANT: Please reset any member data you declared, as 9 // the same Solution instance will be reused for each test case. 10 for(int i = 0; i < result.size(); ++i){ 11 result[i].clear(); 12 } 13 result.clear(); 14 15 int i; 16 int n = num.size(); 17 int nn = 1; 18 19 for(i = 1; i <= n; ++i){ 20 nn *= i; 21 } 22 23 for(i = 0; i < nn; ++i){ 24 result.push_back(vector<int>(num)); 25 next_permutation(num.begin(), num.end()); 26 } 27 28 return result; 29 } 30 private: 31 vector<vector<int>> result; 32 };