Java学习笔记
Leetcode刷题经验
热题HOT100
46、全排列
该题可以很明显地看出来是使用回溯 + 深度优先搜索,使用深度优先搜索的目的是为了更好地使用栈,例如其中存储路径的
p
a
t
h
path
path 。
解题思路:
这里直接借鉴官网的解题思路:
- 需要注意的是为了节省空间,这里采用动态维护数组的方法,而不采用标记数组的形式。
class Solution {
public void backtrack(int n,
ArrayList<Integer> output,
List<List<Integer>> res,
int first) {
if(first ==n)
{res.add(new ArrayList<Integer>(output));}
for(int i =first;i<n;i++){
// 动态维护数组
Collections.swap(output, first, i);
// 继续递归填下一个数
backtrack(n, output, res, first + 1);
// 撤销操作
Collections.swap(output, first, i);
}
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
ArrayList<Integer> output = new ArrayList<Integer>();
for(int num:nums)
output.add(num);
int n = nums.length;
backtrack(n,output,res,0);
return res;
}
}
欢迎大家交流,一起进步!