freeCodeCamp/curriculum/challenges/chinese/10-coding-interview-prep/rosetta-code/count-the-coins.md

1.6 KiB
Raw Blame History

id title challengeType videoUrl dashedName
59713bd26bdeb8a594fb9413 计算硬币 5 count-the-coins

--description--

美国货币有四种常见硬币:

季度25美分硬币10美分5美分和便士1美分

有六种方法可以换15美分

一角钱和一角钱一角钱和5便士3镍2镍和5便士一镍和10便士15便士任务

实现一个功能,以确定使用这些普通硬币改变一美元的方式有多少? 1美元= 100美分

参考: 麻省理工学院出版社的算法

--hints--

countCoins是一个函数。

assert(typeof countCoins === 'function');

countCoints()应该返回242。

assert.equal(countCoins(), 242);

--seed--

--seed-contents--

function countCoins() {

  return true;
}

--solutions--

function countCoins() {
  let t = 100;
  const operands = [1, 5, 10, 25];
  const targetsLength = t + 1;
  const operandsLength = operands.length;
  t = [1];

  for (let a = 0; a < operandsLength; a++) {
    for (let b = 1; b < targetsLength; b++) {
      // initialise undefined target
      t[b] = t[b] ? t[b] : 0;

      // accumulate target + operand ways
      t[b] += (b < operands[a]) ? 0 : t[b - operands[a]];
    }
  }

  return t[targetsLength - 1];
}