回溯算法解题套路框架

一、概念

1、回溯

Back Track

2、步骤

路径、选择列表、结束条件

二、全排列46

class Solution {
    List<List<Integer>> res = new LinkedList<>();
    public List<List<Integer>> permute(int[] nums) {
        LinkedList<Integer> track = new LinkedList<>();
        backtrack(nums,track);
        return res;
    }
    void backtrack(int[] nums, LinkedList<Integer> track){
        //结束条件:路径长度与num相同
        if(track.size() == nums.length){
            res.add(new LinkedList(track));
            return;
        }
        for(int i = 0; i < nums.length; i++){
            if(track.contains(nums[i])) continue;
            //做选择
            track.add(nums[i]);
            backtrack(nums,track);
            //取消选择,list的方法
            track.removeLast();
        }

    }
}

过程

三、N皇后问题

class Solution {
    List<List<String>> res = new LinkedList<>();
    public List<List<String>> solveNQueens(int n) {
        List<char[]> board = new LinkedList<>();
        for(int i = 0; i < n; i++){
            char[] str = new char[n];
            Arrays.fill(str,'.');
            board.add(str);
        }
        backtrack(board,0);
        return res;
    }
    void backtrack(List<char[]> board, int row){
        if(row == board.size()){ //结束条件
            res.add(transform(board));
        }
        int n = board.size();
        for(int col = 0; col < n; col++){
            //遍历所有选择
            if(!isValid(board,row,col)) continue;
            //做选择
            board.get(row)[col]='Q';
            backtrack(board,row+1);
            board.get(row)[col]='.';
        }
    }
    List<String> transform(List<char[]> board){
        //把字符数组列表转换为字符串
        List<String> str = new LinkedList<>();
        for(char[] row : board){
            str.add(new String(row));
        }
        return str;
    }
    Boolean isValid(List<char[]> board, int row, int col){
        int n = board.size();
        for(int i = 0; i < board.size(); i++){
            if(board.get(i)[col]=='Q')
                return false;
        }
        //左上方
        for(int i = row - 1, j = col - 1; i >=0 && j >= 0; i--, j--){
            if(board.get(i)[j] == 'Q')
                return false;
        }
        //右上方
        for(int i = row - 1, j = col + 1; i >=0 && j < n; i--, j++){
            if(board.get(i)[j] == 'Q')
                return false;
        }
        return true;
    }
}

 

posted @ 2021-03-30 15:46  哥们要飞  阅读(96)  评论(0编辑  收藏  举报