Code Monkey home page Code Monkey logo

leetcode's Introduction

Hi, I'm 阿星 (A-Star)

  • 🔭 I’m currently in HangZhou, China
  • 🌱 I’m currently working on FE at Bytedance.

Links

AI技术人的学习资料.md

Visitors

leetcode's People

Contributors

55utah avatar

Watchers

 avatar

leetcode's Issues

【回溯法】算法学习

回溯法

总结下回溯法的解题思路,回溯法比较经典的题目:

46.全排列
51.N 皇后

**:

回溯本质就是DFS算法,属于暴力穷举算法,也就是在做一个决策树的遍历,一般与递归结合。

参考:https://labuladong.github.io/algo/1/4/

回溯核心就是 for 循环里面的递归,在递归调用之前「做选择」。

result = []
def backtrack(路径, 选择列表):
    if 满足结束条件:
        result.add(路径)
        return
    
    for 选择 in 选择列表:
        做选择
        backtrack(路径, 选择列表)

解题模版:

function solve() {
    const result = []
    const go = () => {
         // 判断满足条件
         if (solved) result.push(xxx); return;
         // 做选择,排除不合理选择,进入下一层决策树
         // 遍历子情况,递归处理
         for () {
            go()
         // 有时需要根据上面结果做选择,比如const bool = go(); if (bool) break; 
         // 下一层的其中一个决策树有结果之后,可以停止更多计算,达到剪枝的目的;
         // 这种方法适合于只需寻找一个答案的情况,在找到后停止遍历。
         }
    }
    return result
}

51. N皇后问题 【回溯法】

n 皇后问题

研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
给你一个整数 n ,返回所有不同的 n 皇后问题 的解决方案。
每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中 'Q' 和 '.' 分别代表了皇后和空位。

示例 1:
输入:n = 4
输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
解释:如上图所示,4 皇后问题存在两个不同的解法。
示例 2:
输入:n = 1
输出:[["Q"]]
 
提示:
1 <= n <= 9
皇后彼此不能相互攻击,也就是说:任何两个皇后都不能处于同一条横行、纵行或斜线上。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/n-queens
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


// Typescript版本的回溯法

function solveNQueens(n: number): string[][] {
    if (n == 1) return [['Q']]
    // n个皇后放在n*n的网格内,必定是一行一个,使用一维数组处理
    // 避免通常思维的二维数组,存在复杂度高、引用类型等问题
    // 利用特性降低计算难度,降为一维数组(默认满足了每个皇后左右直线不能有皇后的条件)
    const result = []

    // 使用回溯法思路,从上到下按行遍历,每一行判断棋子可放在哪个位置,然后迭代
    const go = (rows: number[], count: number) => {
        // 已经是n个棋子返回
        if (count >= n) {
            result.push(rows)
            return true
        }
        // 遍历当前行每个位置
        for (let i = 0; i < n; i++) {
            // 斜对角直线上所有位置都不能有棋子
            // 判断 (count, i) 与 (k, j) 元素判断是否对角线 + 本列是否有棋子
            // 满足上下和对角线不能有棋子要求
            const invalid = rows.some((j, k) => Math.abs(count - k) === Math.abs(i - j) || j === i)
            if (!invalid) {
                // 进入下一层迭代
                go(rows.concat(i), count + 1)
            }
        }
    }
    // 初始化数据执行
    go([], 0)
    // 最后再组装输出
    return result.map((row) => {
        return row.map(p => {
            const arr = new Array(n).fill('.')
            arr[p] = 'Q'
            return arr.join('')
        })
    })
};

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.