Permutations [LeetCode]
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]
.
Notes: recursive, in place.
1 class Solution { 2 public: 3 vector<vector<int> > permute(vector<int> &num) { 7 int size = num.size(); 8 vector<vector<int> > result; 9 if(size == 0) 10 return result; 11 if(size == 1) { 12 vector<int> per; 13 per.push_back(num[0]); 14 result.push_back(per); 15 return result; 16 } 17 18 for(int i = 0; i < size; i ++) { 19 int current = num[i]; 20 num.erase(num.begin() + i); 21 vector<vector<int> > ret = permute(num); 22 num.insert(num.begin() + i, current); 23 for(auto item: ret) { 24 item.insert(item.begin(), current); 25 result.push_back(item); 26 } 27 } 28 return result; 29 } 30 };