
class Solution {
public List<List<Integer>> permute(int[] nums) {
ArrayList<List<Integer>> res=new ArrayList<>();
if(nums==null||nums.length==0){
return res;
}
helper(res,new ArrayList<>(),nums);
return res;
}
private void helper(ArrayList<List<Integer>> res,ArrayList<Integer> list,int[] nums){
if(list.size()==nums.length){
res.add(new ArrayList(list));
return;
}
for(int num:nums){
if(list.contains(num)){
continue;
}
list.add(num);
helper(res,list,nums);
list.remove(list.size()-1);
}
}
}
本文介绍了一种基于回溯法的排列算法实现,通过递归函数helper完成对整数数组的所有可能排列。首先创建一个用于存储结果的ArrayList,然后通过判断输入数组是否为空或长度为0来决定是否直接返回空结果。核心部分在于递归调用helper函数,当当前排列的长度等于输入数组长度时,将该排列添加到结果集中;否则,遍历输入数组,将未使用过的元素添加到当前排列中并进行下一层递归。
8万+

被折叠的 条评论
为什么被折叠?



