内容是根据这位博主的修改的
试题 算法训练 加法分解_醒醒,写bug了!的博客-优快云博客_加法拆分算法
#include<iostream>
#include<vector>
using namespace std;
const int N=210;
int n,m,cnt;
int a[N];
void dp1(int u){
if(u==0){
cout<<n<<"=";
for(int i=0;i<cnt;i++){
if(i!=cnt-1)cout<<a[i]<<"+";
else cout<<a[i];
}
cout<<endl;
return;
}
for(int i=1;i<=u;i++){
a[cnt]=i;
cnt++;
dp1(u-i);
cnt--;
}
}
//直接在dp1里加一个判断如果要输出的内容不满足a[i]<=a[i+1]就不输出
void dp2(int u){
if(u==0){
int temp=1;
for(int i=0;i<cnt-1;i++){
if(a[i]>a[i+1]){
temp=0;
break;
}
}
if(temp==1){
cout<<n<<"=";
for(int i=0;i<cnt;i++){
if(i!=cnt-1)cout<<a[i]<<"+";
else cout<<a[i];
}
cout<<endl;
}
return;
}
for(int i=1;i<=u;i++){
a[cnt]=i;
cnt++;
dp2(u-i);
cnt--;
}
}
int main() {
cin>>n>>m;
if(m==1)dp1(n);
else dp2(n);
return 0;
}