[Algorithm] Max icons to include: Dynamic programming

Saying that we have some icons

and a target sum, for example 16.

How to choose which and how many icons to include to reach the target but minize the numbers of icons.

EXP: 3 * 5$ icons 

        +

  1 * 1$icon

-------------

total 4 icons.

Idea is 

 Wheather should include current icon.

const Pair = (i, t) => `Pair(${i}, ${t})`;

const iconsToInclude = (nums, total) => {
  let cache = {};
  const doWork = (i, t) => {
    const p = Pair(i, t);
    if (p in cache) {
      return cache[p];
    }
    if (i === 0 || t === 0 || nums[i] > t) {
      return Number.MAX_SAFE_INTEGER;
    }
    if (t === 1 || nums[i] === t) {
      return 1;
    }
    let toInclude = 0
    let notToInclude = 0;
    let res = 0;
    toInclude = doWork(i, t - nums[i]) + 1;
    notToInclude = doWork(i - 1, t);
    res = Math.min(toInclude, notToInclude);
    cache[Pair(i, t)] = res;
    return res;
  }
  return doWork(nums.length - 1, total);
}

console.log(iconsToInclude([25, 16, 5, 1], 33));
原文地址:https://www.cnblogs.com/Answer1215/p/14296057.html