题目:
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
题解:回溯法
“我们在之前做了什么,这一步做相应的逆操作,这就叫回溯。”
package test;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
class Solution {
public List<List<Integer>> permute(int[] nums) {
int len = nums.length;
List<List<Integer>> res = new ArrayList<>();
if (len == 0) {
return res;
}
Deque<Integer> path = new ArrayDeque<>();//回溯一般用Deque
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));//这里往里面添加的一定是ArrayList类型的
return;
}
for (int i = 0; i < len; i++) {//我记得剪枝这里是从start开始的
if (used[i]) {//如果使用过了,那么继续,下面的就不用执行了。
continue;
}
path.addLast(nums[i]);//往path里面添加的肯定是nums[i]呀
used[i] = true;
dfs(nums, len, depth + 1, path, used, res);
path.removeLast();//我们在之前做了什么,这一步做相应的逆操作,这就叫回溯
used[i] = false;//remove()里面是啥也不加的
}
}
}
public class Main{
public static void main (String []args){
int[] a = {1,2,3};//升序
Solution p = new Solution();
List<List<Integer>> b = p.permute(a);
System.out.println("结果:"+ b);
}
}