【问题标题】:Find Path to Sum - recursion求和路径 - 递归
【发布时间】:2018-12-10 21:55:09
【问题描述】:

作为编码练习之一,我尝试打印路径,您将遇到该路径以找到特定的总和,在本例中为:3。

递增值将是 1 和 2。 因此,求和的最短路径是return [1,2] or [2,1].

但我无法尝试将路径放入数组 - 我已尝试通过参数放置索引,但数组会被覆盖(难怪)。有人可以建议如何解决这个问题吗?

    const toSum = target => {

      const calc = sum => {
        if (sum == target) return 0;
        if (sum > target) return Infinity;

        const temp1 = 1 + calc(sum + 2);
        const temp2 = 1 + calc(sum + 1);

        return Math.min(temp1, temp2);
       };

      return calc(0);
    };

    console.log(toSum(3));

【问题讨论】:

  • 嗨 Tomas Eglinskas 如果您对逻辑有疑问?

标签: recursion dynamic-programming


【解决方案1】:

传递一个数组并用当前添加的值填充它

const toSum = target => {
    const calc = (sum ,res) => {
      if (sum == 0) return res
      if (sum > 2) {
          res.push(2)
          return calc(sum-2,res)
      } 
      res.push(1)
      return calc(sum-1,res)
    };
    
  if (target <1  ) return "need to be above 1" 
  if (!Number.isInteger(target) ) return "need to be an integer"
    return calc(target,[])
  };

console.log(toSum(3));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多