【问题标题】:Coin Change Leetcode C#硬币兑换 Leetcode C#
【发布时间】:2021-10-01 16:31:16
【问题描述】:

我正在寻找使用递归来实现硬币找零问题 (https://leetcode.com/problems/coin-change),并且到目前为止有以下解决方案。问题似乎正常工作,除非:

int[] coins = {2};
int k = 3; 

输出为:-2147483648

预期输出为:-1

解决方法如下:

        static void Main(string[] args)
        {
            int[] coins = {2};
            int k = 3;

            Console.WriteLine(Coin_Change(k, coins));


        }
        public static int Coin_Change(int amount, int[] coins) {

            if (amount == 0) {
                return 0;
            }

            if (amount < 0) {
                return -1;
            }

            int minSteps = int.MaxValue;
            for (int i = 0; i < coins.Length; i++)
            {
                if (coins[i] <= amount)
                {
                    minSteps= Math.Min(minSteps, 1 + Coin_Change(amount - coins[i], coins));
                }

            }
           
            return minSteps;
        }

如何扩展上述解决方案来处理这种情况?

谢谢!

【问题讨论】:

标签: c# recursion dynamic-programming


【解决方案1】:

为了克服这种情况,您需要进行额外检查。

示例代码:

public class Solution {
    int max = 100000008;
    int _go(int[] coins, int amount) {
        if (amount == 0) {
            return 0;
        }

        if (amount < 0) {
            return -1;
        }

        int minSteps = max;
        for (int i = 0; i < coins.Length; i++) {
            if (coins[i] <= amount) {
                minSteps = Math.Min(minSteps, 1 + _go(coins, amount - coins[i]));
            }

        }
        return minSteps;
    }
    public int CoinChange(int[] coins, int amount) {
        int minStep =  _go(coins, amount);
        return minStep >= max ? -1 : minStep;
    }
}

如您所见,我采用了用户定义的最大值。这是因为如果您将 INT_MAX 值作为初始答案,然后尝试使用该值添加一些内容并尝试将其保存在另一个 int 变量中,则会导致您溢出。

我给定的代码会给你正确的输出,你应该给出 -1 作为输出(当你不能用给定的硬币产生目标值的情况下)。

但是使用这种方法不会通过所有测试用例。你会得到 TLE,因为你没有存储任何结果。

这是一个经典的 DP 问题。查看以下资源以了解有关 DP 的更多信息。

Coin Change Problem | Dynamic Programming

Understanding The Coin Change Problem With Dynamic Programming

Coin Change | DP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2020-12-16
    • 2018-04-30
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多