本文主要是介绍【代码随想录】day45,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 一、70爬楼梯 (进阶)
- 二、322零钱兑换
- 三、279完全平方数
一、70爬楼梯 (进阶)
去年春招面试被考过这个题,但当时没写出来。
#include <vector>
#include <iostream>
using namespace std;
int main() {int n, m;cin >> n >> m;std::vector<int> dp(n + 1, 0);dp[0] = 1;for (int i = 1; i < n + 1; i ++) {for (int j = 1; j < m + 1; j ++) {if (i - j >= 0) {dp[i] += dp[i-j];}}}cout << dp[n] << endl;
}
二、322零钱兑换
class Solution {
public:int coinChange(vector<int>& coins, int amount) {vector<int> dp(amount + 1, INT_MAX - 1);dp[0] = 0;for (int j = coins[0]; j < amount + 1; j ++) {if (j % coins[0] == 0) {dp[j] = j / coins[0];}}for (int i = 1; i < coins.size(); i ++) {if (coins[i] > amount) {continue;}for (int j = 1; j < amount + 1; j ++) {if (j >= coins[i]) {dp[j] = min(dp[j], 1 + dp[j-coins[i]]);}}}if (dp[amount] == INT_MAX - 1) return -1;return dp[amount];}
};
初始化总是写不好啊。。。
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 ++) {if (coins[i] > amount) {continue;}for (int j = coins[i]; j < amount + 1; j ++) {if (dp[j-coins[i]] != INT_MAX) {dp[j] = min(dp[j], 1 + dp[j-coins[i]]);}}}if (dp[amount] == INT_MAX) return -1;return dp[amount];}
};
三、279完全平方数
class Solution {
public:int numSquares(int n) {//<=100vector<int> dp(n + 1, 0);for (int j = 1; j < n + 1; j ++) {dp[j] = j;}for (int i = 1; i <= 100 && i * i <= n; i ++) {for (int j = i*i; j < n + 1; j ++) {dp[j] = min(dp[j], 1 + dp[j-i*i]);}}return dp[n];}
};
修改初始化:
class Solution {
public:int numSquares(int n) {vector<int> dp(n + 1, INT_MAX);dp[0] = 0;for (int i = 1; i <= 100 && i * i <= n; i ++) {for (int j = i*i; j < n + 1; j ++) {dp[j] = min(dp[j], 1 + dp[j-i*i]);}}return dp[n];}
};
这篇关于【代码随想录】day45的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!