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: vectorvisit; vector num; vector > res; void dfs(int index , vector & sub){ if(index == num.size()){ res.push_back(sub); return; } for(int i = 0 ; i < num.size(); ++ i){ if(!visit[i]){ visit[i] = true; sub[index] = num[i]; dfs(index+1, sub); visit[i] = false; } } } vector > permute(vector &num) { this->num = num; visit.resize(num.size(),false); vector sub(num.size(),0); dfs(0,sub); return res; }};