Leetcode 322. Coin Change

博客围绕一个问题展开,分析得出这是一个动态规划(DP)问题,可从自上而下或自下而上两个方面求解。还探讨了如何降低时间复杂度和空间复杂度,给出了三种不同复杂度的情况,并包含相关代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem:

在这里插入图片描述

Analysis:

Obviously, this is a DP problem. we can try to figure out it from two aspects. Top to bottom or bottom to Top.

The next step, we should reduce the time complexity and space complexity.

ONE time O(nm^2) space(nm)
在这里插入图片描述

TWO time O(nm) space(nm)

在这里插入图片描述

THREE time O(nm) space(m)

在这里插入图片描述

Code:

public int coinChange1(int[] coins, int amount) {
        
        int[][] f = new int[coins.length + 1][amount + 1];

        Arrays.fill(f[coins.length], Integer.MAX_VALUE);
        f[coins.length][0] = 0;
        
        for (int i=f.length-2;i>=0; i--) {
        	for (int j=0; j<=amount; j++) {
        		
        		f[i][j] = f[i+1][j];
            	for (int k=1; k<=j/coins[i]; k++) {
            		int pre = f[i+1][j-k*coins[i]];
            		if (pre < Integer.MAX_VALUE) {
            			f[i][j] = Math.min( f[i][j], pre+k );
            		}
            		
            	}

            }
        }
         
        if (f[0][amount] == Integer.MAX_VALUE) {
        	return -1;
        }else {
        	return f[0][amount];
        } 
    }



public int coinChange2(int[] coins, int amount) {
        
        int[][] f = new int[coins.length + 1][amount + 1];

        Arrays.fill(f[coins.length], Integer.MAX_VALUE);
        f[coins.length][0] = 0;
        
        for (int i=f.length-2;i>=0; i--) {
        	for (int j=0; j<=amount; j++) {
        		
        		f[i][j] = f[i+1][j];
        		if (j >= coins[i]) {
        			int pre = f[i][j-coins[i]];
        			if (pre < Integer.MAX_VALUE) {
        				f[i][j] = Math.min(f[i][j], pre+1);
        			}
        		}      	
            }
        }
           
        if (f[0][amount] == Integer.MAX_VALUE) {
        	return -1;
        }else {
        	return f[0][amount];
        } 
    }

public int coinChange(int[] coins, int amount) {
		
        int n = coins.length;
        int[] g = new int[amount + 1];
        Arrays.fill(g, Integer.MAX_VALUE);
        g[0] = 0;
        
        for (int i=coins.length-1; i>=0; i--) {
        	for (int j=0; j<=amount; j++) {
        		if (j >= coins[i]) {
        			int pre = g[j-coins[i]];
        			if (pre < Integer.MAX_VALUE) {
        				g[j] = Math.min(g[j], pre+1);
        			}
        		}
        	}
        }
        if (g[amount] == Integer.MAX_VALUE) {
        	return -1;
        }else {
        	return g[amount];
        } 
        
        
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值