518. 零钱兑换 II(leetcode)

https://leetcode.cn/problems/coin-change-ii/description/
可以直接考虑用完全背包的传统二维做法,但是这里求的是组合数,需要注意

在求装满背包有几种方案的时候,认清遍历顺序是非常关键的。

如果求组合数就是外层for循环遍历物品,内层for遍历背包

如果求排列数就是外层for遍历背包,内层for循环遍历物品

class Solution {
    public int change(int amount, int[] coins) {
        // 题意就是一个完全背包问题
        // f[i][j]表示前i个数中选,体积等于j的最大选法种数,答案就是f[n][amount]
        // 以第i个数选多少个来划分子集
        // f[i][j] = f[i-1][j] + f[i][j-conis[i]]
        // f[0][0]=1; // 初值,只有一种选法
        int N = 310;
        int[][] f=new int[N][5010];
        f[0][0]=1; // 什么也不选也是一种选法
        for(int i=1;i<=coins.length;i++)
            for(int j=0;j<=amount;j++)
            {
                // 这里coins需要偏移一位
                if(j>=coins[i-1])f[i][j]=f[i-1][j]+f[i][j-coins[i-1]];
                else f[i][j]=f[i-1][j];
            }
        return f[coins.length][amount];
    }
}

 

posted @ 2024-09-03 16:55  风乐  阅读(8)  评论(0)    收藏  举报