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:
对一个没有重复元素的序列做全排序,可以考虑采用递归的思路。n个元素的全排列为n个元素分别作为第一个元素,并加上分别去除首元素剩下元素的全排列。当序列递归到只有一个元素时,
递归终止,一个可行的全排列产生。
class Solution { public: vector<vector<int> > ans; vector<int> src; int len; void perm(int i) { if(i == len - 1) { //a new permutation comes vector<int> tmp; for(int i = 0;i < len;i++) tmp.push_back(src[i]); ans.push_back(tmp); return; } else { for(int k = i;k < len;k++) { int tmp = src[i]; src[i] = src[k]; src[k] = tmp; perm(i + 1); src[k] = src[i]; src[i] = tmp; } } } vector<vector<int> > permute(vector<int> &num) { len = num.size(); if(len == 0) return ans; src = num; perm(0); return ans; } };