数字全排列:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
回溯思想解决该问题:
1、需要一个长度为数组长度的集合res,将每次满足条件的结果存放进去;同时也需要一个boolean类型的数组,用来判定数组每个索引位置上的元素是否被添加进res中;
boolean[] used = new boolean[num.length];//初始状态下,全为false
2、for循环遍历数组,每拿到数组的一个元素,将该元素存到res中,当res的长度与数组的长度相等时,即是一个满足条件的结果;元素存至res中,
3、采用深度优先遍历、递归,递归终止的条件为:树的深度同数组长度。并将结果返回;
4、再拿到满足条件的结果之后,树的深度需要减1,并且需要将res中末尾的元素取出,(结合1中需要添加至末尾,4需要取出末尾的元素),此处选取栈、或者队列作为res,并且
Deque<Integer> res = new ArrayDeque<Integer>();
res.removeLast();
代码如下:
public List<List<Integer>> permute(int[] nums){
int len = nums.length;
//存储结果
List<List<Integer>> res = new ArrayList<>();
//数组为空时,返回空
if (len == 0){
return res;
}
//向下遍历时,每选中一个数字,将数字入栈
//向上遍历时,高度-1、且出栈一个数子
Deque<Integer> path = new ArrayDeque<Integer>();
//是否选中元素
boolean[] used = new boolean[len];
//进行深度遍历
dfs(nums, len, 0, path, used, res);
return res;
}
private void dfs(int[] nums, int len, int depth, Deque<Integer> path, boolean[] used, List<List<Integer>> res) {
/*
如果树的深度同数组长度,那么是一个正确的结果,将结果返回
*/
if (depth == len){
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < len; i++) {
//如果i被使用,跳过本次循环
if (used[i]){
continue;
}
//将该数字添加至path中
path.addLast(nums[i]);
used[i] =true;
dfs(nums,len, depth+1, path, used, res);
path.removeLast();
used[i] = false;
}
}