Leetcode-322. 零钱兑换个人答案与官方答案的一个对比(以及对测试用例的思考)

题目链接

https://leetcode-cn.com/problems/coin-change/

题目描述

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。

示例 1:

输入: coins = [1, 2, 5], amount = 11
输出: 3 
解释: 11 = 5 + 5 + 1
示例 2:

输入: coins = [2], amount = 3
输出: -1

个人解题代码:

class Solution {
  
  public int coinChange(int[] coins, int amount) {
        int[] f = new int[amount+1];

        if(amount==0){
            return 0;
        }
        for(int i = 0;iamount){
                continue;
            }
            f[coins[i]]=1;
        }

        for(int i =1;i<=amount;i++) {
            if(f[i]==0){
                f[i]=Integer.MAX_VALUE;
            }
        }


        for(int i = 1;i<=amount;i++){

            if(f[i]==Integer.MAX_VALUE ){
                int min = Integer.MAX_VALUE-1;
                for(int j = 0;j=Integer.MAX_VALUE-1?-1:f[amount];
    

    }
}

官方解题代码


public class Solution {
    public int coinChange(int[] coins, int amount) {
        int max = amount + 1;
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, max);
        dp[0] = 0;
        for (int i = 1; i <= amount; i++) {
            for (int j = 0; j < coins.length; j++) {
                if (coins[j] <= i) {
                    dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1);
                }
            }
        }
        return dp[amount] > amount ? -1 : dp[amount];
    }
}

问题——对测试用例的思考

Leetcode-322. 零钱兑换个人答案与官方答案的一个对比(以及对测试用例的思考)_第1张图片

在一次提交中,我遇到了种种情况,当时的我的感受就是,测试用例为何如此刁钻。 Integer.MAX_VALUE 正是2147483647。

我当时差点拉黑了LeetCode,但后来想一想确实是自己错了。

但因为Leetcode用了这样的测试用例,我看了官方解答,之后发现了一个漏洞,倘若我把这个题目中的amount页设置成2147483647,那么官方的代码不久错误了么,果然,在我的操作下,出现了异常。

希望

希望测试用例不要太刁钻把。。。。

你可能感兴趣的:(百练OJ与leetcode)