279. 自然数拆分
完全背包模型
二维
#include<iostream>
using namespace std;
const int N = 4010;
const unsigned int mod = 1 << 31;
unsigned int f[N][N];
int n;
int main(){
cin >> n;
for(int i = 0; i <= n; i ++) f[i][0] = 1;
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= n; j ++){
f[i][j] = f[i - 1][j];
if(j >= i) f[i][j] = (f[i][j] + f[i][j - i]) % mod;
}
cout << f[n][n] - 1 << endl; // 这里可以写成f[n - 1][n]
return 0;
}
一维优化
#include<iostream>
using namespace std;
const int N = 4010;
const unsigned int mod = 1 << 31;
unsigned int f[N];
int n;
int main(){
cin >> n;
f[0] = 1;
for(int i = 1; i <= n; i ++)
for(int j = i; j <= n; j ++)
f[j] = (f[j] + f[j - i]) % mod;
cout << f[n] - 1 << endl;
return 0;
}