Full arrangement-LeetCode

topic:

Insert picture description here
Link: https://leetcode-cn.com/problems/permutations/

Ideas:

  1. This is a typical backtracking algorithm problem. It should be noted that the whole arrangement is in order. 123 and 132 are two results.
  2. The basic idea is depth-first traversal, fix one element at a time (added to temp), and save the current element has been used, and then continue to fix in the remaining elements, when the recursion depth depth and the full arrangement length are equal, save Let’s look at the value of the middle array temp. Here you need to note that temp is a reference and the array needs to be copied
  3. Then go back one level, that is, go back to the last value of temp, and look for other useless values, because after fixing 1, 23 and 32 are the results of backtracking to 1 twice
  4. Repeat the above operation until you have all the way back to the top (empty array)

Code:

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);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_35221523/article/details/112451776