javascript制作更改算法

时间:2017-03-19 06:21:34

标签: javascript algorithm dynamic-programming

我在javascript中解决了这个问题“改变”:

问题:

  

考虑到一定数量的钱,一系列硬币面额,计算出来   使用可用硬币赚钱的方法的数量   面额。

     

示例:

     

对于金额= 4(4¢)和面额= [1,2,3](1¢,   2¢和3¢),您的程序将输出4 - 方法的数量   4美分与这些面额:

     

1¢,1¢,1¢,1¢

     

1¢,1¢,2¢

     

1¢,3¢

     

2¢,2¢

我找到了解决方案:

var makeChange = function(total){
  var count = 0;
  var coins = [1, 2, 5, 10, 20, 50, 100, 200];

  var changer = function(index, value){

    var currentCoin = coins[index];

    if( index === 0){
      if( value % currentCoin === 0){
        count++;
      }
      return;
    }

    while( value >= 0 ){
      changer(index-1, value);
      value -= currentCoin;
    }
  }
  changer(coins.length-1, total);
  return count;
};

makeChange(200);

问题(S):

  1. 有人可以向我解释发生了什么事吗?我试着遵循代码,但我在递归之间迷路了。
  2. 我知道他正在拿最终的硬币价值而且他从给定的总数中减去。 (但为什么?)我有点失落。

    1. 当while循环中的值> = 0时,它会一直循环增加索引,我无法理解原因。
    2. 有人能理解这个算法吗?

      抱歉,刚开始学习动态编程。

      谢谢,

1 个答案:

答案 0 :(得分:1)

让我们跟踪>

的情况

定义函数makeChange(4),然后第一次调用。

changer

由于变量value = 4, index = 7, coins[7] = 200 不为0,我们转到index循环。

使用while 6

changer进行第二次调用
index

好的,现在这个模式继续进行所有函数调用,Meanwhile, the first call continues the 'while' loop but since 200 has been subtracted from 'value', 'value' is now less than 0 so the 'while' loop terminates and this first call does nothing more. (Keep in mind that the variable 'value' is distinct and private to each call, so the 'while' loop only affects the 'value' in its own function call.) 指向大于index的硬币,直到value为1。

index

这次更多发生在value = 4, index = 1, coins[1] = 2 循环中:

while

总计We get the function call, 'changer(0,4)', AND a second function call, 'changer(0,2)', after we subtract 2 from 'value', which was 4, AND a third function call, 'changer(0,0)', after we subtract 2 from 'value', which was 2. These 3 calls respectively represent: 1 + 1 + 1 + 1 2 + 1 + 1 2 + 2 Each time the line 'value -= currentCoin' is executed, it represents the start of another set of choices for solutions that include that coin. 4 % coins[0] = 0, meaning 4 is divisible by 1 represents 1 + 1 + 1 + 1 4 - 2 folllowed by 2 % 1 represents 2 + 1 + 1 and 4 - 2 - 2 represents 2 + 2 count