思路
回溯算法的典型题,将整个过程想象成一颗树的遍历。
1.选择路径
2.递归1-2-3过程
3.退回选择
用数组维护遍历过的元素,数组左侧遍历过,右侧没有遍历过
class Solution {
public:
void dfs (vector<vector<int>>& res, vector<int>& temp, int now, int n) {
if (now == n) {
res.push_back(temp);
return;
}
for (int i = now; i < n; ++i) {
swap(temp[i], temp[now]);
dfs(res, temp, now + 1, n);
swap(temp[i], temp[now]);
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
dfs (res, nums, 0, nums.size());
return res;
}
};