current position:Home>Total permutation problem_ Not containing the same element and containing the same element_ Leetcode46_ Leetcode47_ Backtracking solution + java code

Total permutation problem_ Not containing the same element and containing the same element_ Leetcode46_ Leetcode47_ Backtracking solution + java code

2022-04-29 08:26:46Pipi new zzz

The total permutation problem ( Not containing the same element and containing the same element +Java Backtracking code )


   Total permutation is a very classical algorithm problem , It can be roughly divided into two categories : The first is the total permutation problem without the same elements ; The second is the total permutation problem with the same elements . The latter because the sequence contains the same elements , So there will be a lot of repeated answers , The key to the question is to eliminate this repeated answer . Once we write the code for two kinds of permutation problems , Once and for all , Use them as templates .

1 The total permutation problem without the same elements

1.1 Problem description

   For problem description, see Leetcode46 topic .

1.2 Their thinking

   Adopt the basic idea of backtracking , By setting up a visited Array Mark whether each element in the original sequence has been accessed , Recursively output all possible permutations of the problem . It should be noted that , After each recursion , To recover visited The state of the array , Otherwise, it will affect the judgment behind the program .

1.3 Java Code
import java.util.*;

public class Question_46 {
    

    public List<List<Integer>> permute(int[] nums) {
    
    	// Use one List Store all possible permutations 
        List<List<Integer>> res = new ArrayList<>();
        //visited Array , Indicates whether the element at that location has been accessed 
        boolean[] visited = new boolean[nums.length];
        backtrack(res, nums, visited, new ArrayList<Integer>());
        return res;
    }

    private void backtrack(List<List<Integer>> res, int[] nums, boolean[] visited, ArrayList<Integer> tmp) {
    
    	// If the number of elements in the current sequence is equal to nums Length of array , Then this is a possible solution , Join in res in 
        if (tmp.size() == nums.length) {
    
        	// Be careful not to directly join tmp
            res.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
    
        	// If accessed , return 
            if (visited[i]) {
    
                continue;
            }
            visited[i] = true;
            tmp.add(nums[i]);
            backtrack(res, nums, visited, tmp);
            // After use , Return to initial state 
            visited[i] = false;
            tmp.remove(tmp.size() - 1);
        }
    }

}

2 The total permutation problem with the same elements

2.1 Problem description

   For problem description, see Leetcode47 topic .

2.2 Their thinking

   Still use the basic idea of backtracking , The difference is that we need to eliminate the repeated answers caused by the same elements in the sequence . The solution is : Sort the array first ( Put the same elements together , Keep them close to each other ), And then when you go back , Only when the previous same element has been accessed , To access the next same element ( Of course, it can also be set to only when the previous same element has not been accessed , To access the next same element , This represents two permutations , The results are the same ).

2.3 Java Code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Question_47 {
    

    public List<List<Integer>> permuteUnique(int[] nums) {
    
        List<List<Integer>> permutes = new ArrayList<>();
        List<Integer> permuteList = new ArrayList<>();
        // You need to sort the array in advance , Put the same elements together 
        Arrays.sort(nums);
        boolean[] hasVisited = new boolean[nums.length];
        backtracking(permuteList, permutes, hasVisited, nums);
        return permutes;
    }

    private void backtracking(List<Integer> permuteList, List<List<Integer>> permutes, boolean[] visited, int[] nums) {
    
    	// If the number of elements in the current sequence is equal to nums Length of array , Then this is a possible solution , Join in permutes in 
        if (permuteList.size() == nums.length) {
    
        	// Be careful not to directly join permuteList
            permutes.add(new ArrayList<>(permuteList));
            return;
        }

        for (int i = 0; i < visited.length; i++) {
    
        	// This is set to only when the previous same element has been accessed , To access this element , Of course, it can also be set to only when the previous same element has not been accessed , To access the current element , These two orders are represented by , The results are the same 
            if (i != 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
    // Or you could write it as (i != 0 && nums[i] == nums[i - 1] && visited[i - 1])
                continue;// Prevent duplication 
            }
            if (visited[i]) {
    
                continue;
            }
            visited[i] = true;
            permuteList.add(nums[i]);
            backtracking(permuteList, permutes, visited, nums);
            // After use , Return to initial state 
            permuteList.remove(permuteList.size() - 1);
            visited[i] = false;
        }
    }

}

copyright notice
author[Pipi new zzz],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290604385769.html