#include<iostream>
using namespace std;
#define M 100
void main(){
int x[M],Y[M];
int n,y,sum=0,k=0;
cout<<"请输入数组x的个数:";
cin>>n;
for(int i=0;i<n;i++){
cout<<"x"<<(i+1)<<": ";
cin>>x[i];
}
for(int b=0;b<n;b++){
Y[b]=2;
}
cout<<"请输入正整数y: ";
cin>>y;
while(k>=0){
Y[k]=Y[k]-1;
if((Y[k]==1||Y[k]==0)&&k<n){
sum=sum+(Y[k]?x[k]:0);
if(sum==y) break;
else if(sum<y){
k++;
}
else{
sum=sum-(Y[k]?x[k]:0);
}
}
else{
Y[k]=2;
k--;
sum=sum-(Y[k]?x[k]:0);
}
continue;
}
for(int z=0;z<n;z++){
cout<<x[z]<<" ";
}
cout<<endl;
for(int a=0;a<n;a++){
cout<<Y[a]<<" ";
}
cout<<endl;
cout<<"即:取";
for(int c=0;c<n;c++){
if(Y[c]==1){
cout<<x[c]<<" ";
}
}
cout<<"相加"<<endl;
}
回溯法求和 算法设计
最新推荐文章于 2019-07-18 13:54:43 发布