题目
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
题解
采用回溯法。
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
LinkedList<Integer> path = new LinkedList<>();
backtrack(nums, path);
return res;
}
/**
路径:记录在track中
选择列表:nums中不存在于track中的元素
终止条件:nums中的元素全部出现在track中
*/
void backtrack(int[] nums, LinkedList<Integer> path){
// 触发终止条件
if(nums.length == path.size()){
res.add(new LinkedList(path)); //复制一个path加入结果集
return;
}
// 遍历
for(int i = 0; i < nums.length; i++){
// 排除不合法的旋转
if(path.contains(nums[i]))
continue;
// 添加元素
path.add(nums[i]);
// 进入下一层决策树
backtrack(nums, path);
// 恢复原状
path.removeLast();
}
}
}