题目:给定一个不含重复数字的数组 nums
,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
思路:排列问题是有序的,需要一个used数组,标记已经选择的元素。
第一步:确定参数与返回值。参数为数组nums,无返回值。排列问题不需要startIndex,因为排列问题是有序的,每次都要从头开始遍历
第二步:确定终止条件。当收集元素的数组path的大小达到和nums数组一样大的时候,说明找到了一个全排列,也表示到达了叶子节点。将结果加入结果集中
第三步:确定单层递归逻辑。for循环遍历nums数组,区间为整个数组。如果nums[i]用过,则跳过本轮循环,否则,将used[i]设为true,代表使用了该元素,将nums[i]加入path中,递归数组中剩余的元素,回溯。
代码:
List<List<Integer>> result=new ArrayList<>();
List<Integer> path=new ArrayList<>();
boolean[] used;//记录元素的使用情况
public List<List<Integer>> permute(int[] nums) {
if(nums.length==0)
return result;
used=new boolean[nums.length];
backTracking(nums);
return result;
}
public void backTracking(int[] nums){
if(path.size()==nums.length){
result.add(new ArrayList(path));
return;//只要树的叶节点就要return,要树的所有节点不return
}
for(int i=0;i<nums.length;i++){
if(used[i])
continue;
//处理
used[i]=true;
path.add(nums[i]);
//递归
backTracking(nums);
//回溯
path.removeLast();
used[i]=false;
}
}