改成dfs(nextIndex, steps + +),为啥leetcode报错呢?

 var numWays = function(n, relation, k) {
  let ways = 0;
  const edges = new Array(n).fill(0).map(() => new Array());

  for (const [src, dst] of relation) {
      edges[src].push(dst);
  }

  const dfs = (index, steps) => {
      if (steps === k) {
          if (index === n - 1) {
              ways++;
          }
          return;
      }
      const list = edges[index];
      for (const nextIndex of list) {
          dfs(nextIndex, steps + 1);
      }
  }
  
  dfs(0, 0);
  return ways;
}
var relation = [[0,2],[2,1],[3,4],[2,3],[1,4],[2,0],[0,4]]
numWays(5,relation,3)

报错:
maximum call stack size exceed
不改不报错

阅读 1.3k
1 个回答

这不就 i++++i 是谁先自增后使用、谁先使用后自增的问题么……

function print(val) {
    console.log(val);
}

let i = 1, j = 1;
print(i++); // 1
print(++j); // 2

你这里一直在用同一个 steps 的值,递归死循环了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题