题目描述:
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路:
回溯
通过答案:
class Solution {public List<List<Integer>> permute(int[] nums) {List<List<Integer>> res=new ArrayList<>(); List<Integer> path=new ArrayList<>(); //保存状态变量,相当于一个栈int len=nums.length;boolean[] used=new boolean[len]; //标记该元素是否已经使用过了if(len==0)return res;dfs(nums,len,0,path,used,res); //深度遍历return res;}private void dfs(int[] nums,int len,int deep,List<Integer> path,boolean[] used,List<List<Integer>> res){if(deep==len){ //递归的终止条件为,数已经选够了res.add(new ArrayList<>(path)); //将状态变量添加到结果数组resreturn;}for(int i=0;i<len;i++){if(!used[i]){ //当元素未使用过path.add(nums[i]); //添加状态变量used[i]=true; //设为使用过dfs(nums,len,deep+1,path,used,res); //往深层递归used[i]=false; //由深层回到浅层,状态需要重置path.remove(path.size()-1); //删除每次回溯的最后一个元素}}}
}