小编clu*_*luv的帖子

这种递归如何工作?

这是Eloquent Javascript的一个例子:

从数字1开始并重复加5或乘3,可以产生无限量的新数.你会如何编写一个函数,给定一个数字,试图找到一个产生该数字的加法和乘法序列?

我无法理解递归在这里如何工作,想知道是否有人可以写出几次如何调用查找或其他解释.

function findSequence(goal) {
  function find(start, history) {
    if (start == goal)
      return history;
    else if (start > goal)
      return null;
    else
      return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");
  }
  return find(1, "1");
}

console.log(findSequence(24)); // => (((1 * 3) + 5) * 3)
Run Code Online (Sandbox Code Playgroud)

javascript algorithm recursion

5
推荐指数
1
解决办法
477
查看次数

确定复杂性等级

这里有什么重要的记号?一个解释将不胜感激.谢谢.

public static int[] mystery1(int[] list) {

  int[] result = new int[2 * list.length];
  for (int i = 0; i < list.length; i++) {
    result[2 * i] = list[i] / 2 + list[i] % 2;
    result[2 * i + 1] = list[i] / 2;
  }

  return result;

}
Run Code Online (Sandbox Code Playgroud)

java performance complexity-theory big-o

2
推荐指数
1
解决办法
304
查看次数