js算法常用模板(更新中...)

147 阅读1分钟

宽度优先搜索

什么时候用BFS

  • 图的层次遍历
  • 图的连通性
  • 简单图的最短路径
  • 拓扑排序

1. 树的BFS

var levelOrder = function(root) {
    if(root == null) return [];
    let q = [root];
    
    while(q.length) {
        let len = q.length;
        while(len--) {
            let node = q.shift();
           
            if(node.left) q.push(node.left);
            if(node.right) q.push(node.right);
        }
    }
};

模板题:leetcode-cn.com/problems/bi…

深度优先搜索

什么时候用DFS?

  • 排列
  • 组合
// 给定一个数组求所有的子集
var subsets = function(nums) {
    let res = [];
    if(nums == null) return res;
    if(nums.length == 0) {
        res.push([]);
        return res;
    }
    nums.sort((a, b) => a - b);
    dfs(nums, 0, [], res);
    return res;
};

var dfs = function(nums, startIndex, combination, res) {
    res.push(combination.slice());
    
    for(let i = startIndex; i < nums.length; i++) {
        combination.push(nums[i]);
    
        dfs(nums, i + 1, combination, res);

        combination.pop();
    }
    
}

模板题:leetcode-cn.com/problems/po…

前缀和

用于快速求一段区间的和

let s = new Array(arr.length + 1).fill(0);
    
for(let i = 0; i < arr.length; i++) s[i + 1] = s[i] + arr[i];

// 区间[l, r]的和为s[r] - s[l]

模板题: leetcode-cn.com/problems/su…