Javascript Solution: What's wrong?


  • 0
    M

    This fails on change(500, [2, 7, 13])
    Result: 404
    Answer: 717

    Anyone know what is wrong?

    /**
     * @param {number} amount
     * @param {number[]} coins
     * @return {number}
     */
    var change = function(amount, coins) {
      var dp = [1];
      
      for (var i = 0; i < coins.length; ++i) {
          for (var j = coins[i]; j <= amount; ++j) {
              if (!dp[j])
                dp[j] = 0;
              dp[j] += dp[j - coins[i]];
          }
      }
      
      return dp[amount] || 0;
    };
    

  • 0
    D

    @michaelsmith.a said in Javascript Solution: What's wrong?:

    dp[j - coins[i]]

    Be careful about the undefined value,
    change dp[j - coins[i]] to (dp[j - coins[i]] || 0) will fix that.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.