代码随想录算法训练营第四十五天| 卡码网:57. 爬楼梯 、322. 零钱兑换、279.完全平方数
卡码网:57. 爬楼梯
题目链接 文章讲解
# include <bits/stdc++.h>
using namespace std;
int main ( ) {
int n, m;
cin >> n >> m;
vector< int > dp ( n + 1 , 0 ) ;
dp[ 0 ] = 1 ;
for ( int i = 1 ; i <= n; i++ ) {
for ( int j = 1 ; j <= m; j++ ) {
if ( i < j) continue ;
dp[ i] += dp[ i - j] ;
}
}
cout << dp[ n] << '\n' ;
return 0 ;
}
322. 零钱兑换
题目链接 文章讲解
class Solution {
public :
int coinChange ( vector< int > & coins, int amount) {
int n = coins. size ( ) ;
vector< int > dp ( amount + 1 , INT32_MAX) ;
dp[ 0 ] = 0 ;
for ( int i = 0 ; i < n; i++ ) {
for ( int j = coins[ i] ; j <= amount; j++ ) {
if ( dp[ j - coins[ i] ] == INT32_MAX) continue ;
dp[ j] = min ( dp[ j] , dp[ j - coins[ i] ] + 1 ) ;
}
}
return dp[ amount] == INT32_MAX ? - 1 : dp[ amount] ;
}
} ;
279.完全平方数
题目链接 文章讲解
class Solution {
public :
int numSquares ( int n) {
vector< int > dp ( n + 1 , INT32_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] ;
}
} ;