求输入数组的全排列输出。
我是用经典的递归思路求解的:
1. 当输入数组num只有一个元素,将num压入ret, 返回;(递归终止条件)
2. 假设num中的元素个数为N,取出num的最后一个元素,记为b
求出num[0..N-2]的全排列,将b插入所有可能的位置,得到完整的全排列结果
这道题还有其它思路,已经有人做了讨论,戳这里
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]
.
代码
class Solution { public: vector<vector<int> > permute(vector<int> &num) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<vector<int>> p; if(num.size() == 0) return p; if(num.size() == 1) { p.push_back(num); return p; } int nsize = num.size(); int belem = num[nsize-1]; // get the last element in input vector num.pop_back(); // partial permulation result vector<vector<int>> subp = permute(num); int ssize = subp.size(); for(int i=0; i<ssize; ++i) { vector<int> seq = subp[i]; int qsize = seq.size(); // insert belem at all possible positions for(int j=0; j<qsize; ++j) { seq.insert(seq.begin()+j, belem); p.push_back(seq); seq.erase(seq.begin()+j); } seq.push_back(belem); p.push_back(seq); } return p; } };