算法之禅-抛硬币

namespace NDNGH;

public class DTGH{
    public static int Change(int n)
    {
        int minCount = -1, time = 0;
        for(int c5 = 0; c5 < n / 5; c5++)
        {
            for(int c3 = 0; c3 < n / 3; c3++)
            {   
                for(int c2 = 0; c2 < n / 2; c2++)
                {      
                    time ++;
                    if(c2*2 + c3*3 + c5*5 == n){
                        var count = c2+c3+c5;
                        if (minCount > count || minCount == -1)
                        {
                            minCount = count;
                        }
                    }
                }
            }
        }
        System.Console.WriteLine( $"循环次数:{time}");
        return minCount;
    }

    public static int Change2(int[] coins,int n)
    {
        if(n == 0)return 0;
        var optimal = new int[n + 1];
        Array.Fill(optimal, -1);
        foreach(var coin in coins) optimal[coin] = 1;
        for (int v = 1; v <= n; v++)
        {
            if (optimal[v] != -1) continue;
            foreach(var coin in coins)
            {
                if (v - coin < 0 || optimal[v-coin] == -1) continue;
                if (optimal[v] == -1 || optimal[v - coin] + 1 < optimal[v])// 这个条件是否符合最小
                {
                    optimal[v] = optimal[v-coin] + 1;
                } 
            }
        }
        return optimal[n];
    }

    // 21最少可以用多少硬币(2,3,5)兑换。
    public static int Change3(int[] coins,int n)
    {
        if (n<=0)return -1;
        int[] op = new int[n + 1];
        foreach(var coin in coins)op[coin] = 1;
        for(int v = 1;v<=n;v++)
        {
            foreach(var coin in coins){
                // 不能兑换条件。小于币值,兑换当前币值后小于无法兑换
                if(op[v] == -1 || op[v-coin] == -1) continue;
                if(op[v] == -1 || op[v - coin] + 1< op[v])
                {
                    op[v] = op[v-coin] + 1;
                }
            }
        }
        return op[n];
    }

    // 递归版本:
    // 1.我想知道21最少需要多少硬币
    // 2.只需要知道 16,18,19中最少需要硬币+1
    // 3.。。。
    // 4.递归结束条件:n=币值
    public static int Change4(int[] coins, int n, int[] cache)
    { 
        var optimal = -1;
        if (n <= 0) return optimal;
        if(cache[n] == 1) return cache[n];
        foreach (var coin in coins)
        {
            if (n == coin) return 1;
            var subOptimal = Change4(coins, n - coin,cache);
            if (subOptimal == -1) continue;
            if (optimal == -1 || optimal > subOptimal + 1)
            {
                optimal = subOptimal + 1;
                cache[n] = optimal;
            }
        }
        return optimal;
    }
}

 

posted @ 2023-03-19 20:33  vba是最好的语言  阅读(28)  评论(0编辑  收藏  举报