518. 零钱兑换 II

传送门:https://leetcode-cn.com/problems/coin-change-2/

 

和01背包不同的是,硬币的数量是无限的,可以随便用,所以把从尾到0的for循环反过来写就行了。

class Solution 
{
public:
    int change(int amount, vector<int>& coins) 
    {
        int bag[5000 + 1] = { 0 };
        bag[0] = 1;
        for ( auto tmp : coins )
        {
            for ( int i = 0; i <= amount - tmp; ++i)
            {
                if ( bag[i] > 0 )
                {
                    bag[i + tmp] += bag[i];
                }
            }
        }
        return bag[amount];
    }
};

 

posted on 2021-06-10 14:42  LLawliet  阅读(38)  评论(0编辑  收藏  举报

导航