简介
使用回溯算法来解这道题比较简单。
code
class Solution {
public List<List<Integer>> res;
public void dfs(Deque<Integer> path, boolean[] used, int[] nums){
if(nums.length == path.size()){
res.add(new ArrayList<>(path));
return;
}
for(int i=0; i<nums.length; i++){
if(used[i]){
continue;
}
path.addLast(nums[i]);
used[i] = true;
dfs(path, used, nums);
used[i] = false;
path.removeLast();
}
}
public List<List<Integer>> permute(int[] nums) {
res = new ArrayList<List<Integer>>();
if(nums.length == 0){
return res;
}
boolean [] used = new boolean[nums.length];
Deque<Integer> path = new ArrayDeque<Integer>();
dfs(path, used, nums);
return res;
}
}
class Solution {
public:
vector<vector<int>> res;
public:
void dfs(vector<bool> &used, vector<int> &path, vector<int>& nums, int depth){
if(path.size() == nums.size()) {
res.push_back(path);
return;
}
for(int i=0; i<nums.size(); i++){
if(used[i]){
continue;
}
used[i] = true;
path.push_back(nums[i]);
dfs(used, path, nums, depth+1);
path.pop_back();
used[i] = false;
}
}
vector<vector<int>> permute(vector<int>& nums) {
if(nums.size() == 0){
return res;
}
vector<bool> used(nums.size(), false);
vector<int> path;
dfs(used, path, nums, 0);
return res;
}
};