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) { result.clear(); dfs(num,0); return result; } void dfs(vector<int> num, int depth) { if(depth == num.size()-1) { result.push_back(num); return; } dfs(num,depth+1); int temp = num[depth]; for(int i = depth+1;i< num.size(); i++) { num[depth] = num[i]; num[i] = temp; dfs(num,depth+1); num[i] = num[depth]; num[depth] = temp; } } private: vector<vector<int> > result; };
时间: 2024-12-26 20:20:10