46. 全排列
回溯
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] vis;
public List<List<Integer>> permute(int[] nums) {
vis = new boolean[nums.length];
backtrack(nums);
return res;
}
void backtrack(int[] nums){
if(path.size() == nums.length){
res.add(new ArrayList<>(path));
return;
}
for(int i = 0; i < nums.length; i++){
if(vis[i]) continue;
path.add(nums[i]);
vis[i] = true;
backtrack(nums);
vis[i] = false;
path.remove(path.size() - 1);
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27