总流程是递归:参考
方法一:用visited记录是否遍历
class Solution {public: vector> permute(vector &num) { vector > res; vector out; vector visited(num.size(), 0); permuteDFS(num, 0, visited, out, res); return res; } void permuteDFS(vector &num, int level, vector &visited, vector &out, vector > &res) { if (level == num.size()) res.push_back(out); else { for (int i = 0; i < num.size(); ++i) { if (visited[i] == 0) { visited[i] = 1; out.push_back(num[i]); permuteDFS(num, level + 1, visited, out, res); out.pop_back(); visited[i] = 0; } } } }};
方法二:交换数字
class Solution {public: vector> permute(vector &num) { vector > res; permuteDFS(num, 0, res); return res; } void permuteDFS(vector &num, int start, vector > &res) { if (start >= num.size()) res.push_back(num); for (int i = start; i < num.size(); ++i) { swap(num[start], num[i]); permuteDFS(num, start + 1, res); swap(num[start], num[i]); } }};