[41] Backtracking Method-Full Permutation | N Queen's Problem (LC 46 | 51)

Detailed backtracking algorithm

Solving a backtracking problem is actually a traversal process of a decision tree.

Two kinds of decision tree traversal:
Insert picture description here
as above, the parameter t is the number of layers currently in the decision tree.

Subset tree: for selecting a subset that satisfies the condition in the solution vector), such as the knapsack problem;

Permutation tree: for the sorting problem of the solution vector, such as full permutation, eight queens problem.

Permutation problem

Problem Description

Given a sequence without repeated numbers, return all possible permutations.

Problem-solving thoughts

Obviously, this problem is a sorting problem of solution vectors, and the template of traversing the arrangement tree can be directly applied:

class Solution {
    
    
    public List<List<Integer>> permute(int[] nums) {
    
    
        List<List<Integer>> res = new ArrayList<List<Integer>>();

        List<Integer> path = new ArrayList<Integer>();
        for (int num : nums) {
    
    
            path.add(num);
        }

        int n = nums.length;
        backtrack(n, path, res, 0);
        return res;
    }

    public void backtrack(int n, List<Integer> path, List<List<Integer>> res, int t) {
    
    
        if (t >= n) {
    
    //到了最后一层
            res.add(new ArrayList<Integer>(path));
        }
        for (int i = t; i < n; i++) {
    
    
            Collections.swap(path, t, i);//swap(List list,int i,int j):交换集合中指定元素索引的位置
            backtrack(n, path, res, t + 1);
            Collections.swap(path, t, i);
        }
    }
}

Time complexity: O(n!)
Space complexity: O(n)

N queen problem

Problem Description

The n queen problem studies how to place n queens on an n×n chessboard and make the queens unable to attack each other.

Give you an integer n, and return all the different solutions to the n-queen problem.

Each solution contains a different chess placement plan for the n-queen problem, where'Q' and'.' represent the queen and the empty position, respectively.

Note:

1 <= n <= 9
Queens cannot attack each other, which means that no two queens can be on the same horizontal, vertical or diagonal line.

Problem-solving ideas

Because there must be n queens on the n*n chessboard, and because the queens cannot be in the same row, the same column and the same diagonal, there must be one queen in each row. Then suppose the queen's coordinates on the column are xi, xi It means that the queen of the i-th row is in the xi-th column, xi∈(0,...,n-1). From this, it can be seen that the problem is a permutation problem of the solution vector, and the template of the permutation tree can be applied. In fact, this problem can also be solved with a subset tree.

Different from the full arrangement problem, this problem needs to consider the pruning problem, if the placement rules are not met, then pruning:

For the queen in row i and the queen in row j:
1) The two queens are not in the same column: xi != xj;
2) The two queens are not on the same diagonal: | ij | != | xi-xj|

class Solution {
    
    
    public List<List<String>> solveNQueens(int n) {
    
    
        List<List<String>> res = new ArrayList<List<String>>();
        int row[] = new int[n];//用row存储皇后在列上的排列顺序
        backtrack(res,row,n,0);
        return res;
    }

    public void backtrack(List<List<String>> res,int[] row,int n,int t){
    
    //遍历子集树
        if(t >= n)
            output(res,row,n);
        else{
    
    
            for (int i = 0; i < n; i++){
    
    
                row[t] = i;
                if(legal(row,t))
                    backtrack(res,row,n, t+1);
            }
        }
    }

    public boolean legal(int[] row,int t){
    
     //判断是否为有效的坐标
        for(int i=0;i<t;i++){
    
    
            if(Math.abs(i-t)==Math.abs(row[i]-row[t]) || row[i]==row[t])
                return false;
        }
        return true;
    }

    public void output(List<List<String>> res,int[] row,int n){
    
     //打印结果
        List<String> temp_res = new ArrayList<String>();
        for(int i=0;i<n;i++){
    
    
            String line = "";
            for(int j=0;j<n;j++){
    
    
                if(j == row[i])
                    line = line + 'Q';
                else
                    line = line + '.';
            }
            temp_res.add(line);
        }
        res.add(temp_res);
    }
}

Time complexity: O(2^n)
Space complexity: O(n)

Guess you like

Origin blog.csdn.net/qq_43424037/article/details/114293727