全排列-LeetCode

题目:

在这里插入图片描述
链接:https://leetcode-cn.com/problems/permutations/

思路:

  1. 这是一道典型的回溯算法题,需要注意的是全排列是有顺序之分的,123和132是两个结果
  2. 基本思路就是深度优先遍历,每次固定一个元素(添加至temp中),并保存当前元素已经被使用used,然后在剩下的元素中继续固定,当递归深度depth和全排列长度相等时,保存一下中间数组temp的值,这里需要注意temp是引用,需要复制数组
  3. 然后向上回溯一层,即回退temp的最后一个值,找找有没有别的没用的值,因为固定了1之后,23和32是两次回溯到1之后的结果
  4. 重复上面的操作,直到一直回溯到最顶层(空数组)

代码:

import java.util.ArrayList;
class Solution {
    
    
    public List<List<Integer>> permute(int[] nums) {
    
    
        int len = nums.length;
        List<List<Integer>> result = new ArrayList<>();
        if(len==0) return result;

        // 保存排列的中间结果
        List<Integer> temp = new ArrayList<>();
        // 开关数组,记录此次排列的当前元素是否被使用
        boolean[] used = new boolean[len];
        dfs(nums, len, 0, temp, result, used);
        return result;
    }
    
    public void dfs(int[] nums, int len, int depth, List<Integer> temp, List<List<Integer>> result, boolean[] used){
    
    
        // 出现全排列,保存此时temp的结果
        if(depth==len){
    
    
            result.add(new ArrayList<>(temp));
            return;
        }
        for(int i=0;i<len;i++){
    
    
            // 该元素已经使用过
            if(used[i]){
    
    
                continue;
            }
            // 记录状态值
            used[i] = true;
            temp.add(nums[i]);
            // 深度优先遍历,直到找到一个全排列
            dfs(nums,len,depth+1,temp,result,used);
            // 回溯,逆操作状态值
            used[i] = false;
            temp.remove(temp.size()-1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35221523/article/details/112451776