整数划分
和完全背包很像
法一:
#include <iostream>
using namespace std;
const int mod=1e9+7;
const int N=1010;
int dp[N][N];
int main(){
int n;
scanf("%d",&n);
for (int i = 0; i <= n; i ++)dp[i][0] = 1;
for(int i=1;i<=n;i++){
for(int j=0;j<=n;j++){
dp[i][j]=dp[i-1][j]%mod;
if(j>=i)dp[i][j]=(dp[i-1][j]+dp[i][j-i])%mod;
}
}
printf("%d",dp[n][n]);
return 0;
}
化简
#include <iostream>
using namespace std;
const int mod=1e9+7;
const int N=1010;
int dp[N];
int main(){
int n;
scanf("%d",&n);
for (int i = 0; i <= n; i ++)dp[0] = 1;
for(int i=1;i<=n;i++){
for(int j=0;j<=n;j++){
if(j>=i)dp[j]=(dp[j]+dp[j-i])%mod;
}
}
printf("%d",dp[n]);
return 0;
}
法二:
#include <iostream>
using namespace std;
const int mod=1e9+7;
const int N=1010;
int dp[N][N];
int main(){
int n,ans=0;
scanf("%d",&n);
dp[0][0]=1;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
dp[i][j]=(dp[i-1][j-1]+dp[i-j][j])%mod;
}
}
for(int i=1;i<=n;i++){
ans=(ans+dp[n][i])%mod;
}
printf("%d",ans);
return 0;
}