给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [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> sub_res = new ArrayList<>();
if(nums.length==0){return res;}
p_dfs(res,nums,sub_res);
return res;
}
public void p_dfs(List<List<Integer>> res,int[] nums,List<Integer> sub_res){
if(sub_res.size()==nums.length){
res.add(new ArrayList<>(sub_res));
}
else{
for(int i=0;i<nums.length;i++){
if(!sub_res.contains(nums[i])){
sub_res.add(nums[i]);
p_dfs(res,nums,sub_res);
sub_res.remove(sub_res.size()-1);
}
}
}
}
}
此题可深入了解for循环嵌套递归的用法。