代码随想录算法训练营第四十五天|57.爬楼梯、322.零钱兑换、279.完全平方数

文档链接:https://programmercarl.com/

LeetCode57.爬楼梯

题目链接:https://kamacoder.com/problempage.php?pid=1067

思路:每个物品能用多次——完全背包。求排列,遍历顺序要先背包后物品。

动规:

#include<iostream>
#include<vector>
using namespace std;
int main() {
    int n, m;
    cin >> n >> m;
    
    vector<int> dp(n + 1, 0);
    dp[0] = 1;
    for(int j = 0; j <= n; j++) {
        for(int i = 0; i < m; i++) {
            if(j >= (i + 1)) dp[j] += dp[j - (i + 1)];
        }
    }
    cout << dp[n] << endl;
    return 0;
}

LeetCode322.零钱兑换

题目链接:https://leetcode.cn/problems/coin-change/description/

思路:成功AC!

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

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

动规:

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        vector<int> dp(amount + 1, INT_MAX);
        dp[0] = 0;
        for(int i = 0; i < coins.size(); i++) {
            for(int j = coins[i]; j <= amount; j++) {
                if(dp[j - coins[i]] != INT_MAX) dp[j] = min(dp[j], dp[j - coins[i]] + 1);
            }
        }
        if(dp[amount] == INT_MAX) return -1;
        else return dp[amount];
    }

LeetCode279.完全平方数

题目链接:https://leetcode.cn/problems/perfect-squares/

思路:同上一题

动规:

class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n + 1, INT_MAX);
        dp[0] = 0;
        for(int i = 1; i * i <= n; i++) {
            for(int j = i * i; j <= n; j++) {
                dp[j] = min(dp[j], dp[j - i * i] + 1);
            }
        }
        return dp[n];
    }
};

总结:有感觉了哦!

  • 19
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值