对于递归转到非递归问题 ,一般都是 自己构造一个栈。
/*#include<stdio.h>
int knap(int w[],int v,int n){
if(v == 0) return 1;
else{
if(v < 0 || (v>0 && n<1)) return 0;
else{
if(knap(w,v-w[n-1],n-1)==1){
printf("result:n = %d,w[%d] = %d\n",n,n-1,w[n-1]);
return 1;
}
else return knap(w,v,n-1);
}
}
}
int main(){
int w[5] = {1,4,4,5,7};
int n = 5;
int v = 10;
knap(w,v,n);
return 0;
}*/
#include<stdio.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct{
ElemType data[MAXSIZE];
int top;
}SqStack;
void Init_SqStack(SqStack &S) {S.top = -1;}
int Empty_SqStack(SqStack &S){
if(S.top == -1) return 1;
else return 0;
}
void Push_SqStack(SqStack &S,ElemType x){
if(S.top == MAXSIZE -1) return ;
else S.data[++S.top] = x;
}
void Pop_SqStack(SqStack &S,ElemType &e){
if(Empty_SqStack(S)){
return;
}
else{
e = S.data[S.top];
S.top --;
}
}
int knap(int w[],int v,int n){
SqStack S;
int j,k;
Init_SqStack(S);
k = 0;
do{
while(v>0 && k<n){
if(v-w[k]>=0){
Push_SqStack(S,k);
v-=w[k];
}
k++;
}
if(v == 0){
printf("\nresult:\n");
for(j = 0;j<=S.top;j++){
printf("n=%d,w[%d] = %d\n",S.data[j]+1,S.data[j],w[S.data[j]]);
}
}
Pop_SqStack(S,k);
v+=w[k];
k++;
}while(!Empty_SqStack(S) || k!=n);
}
int main(){
int w[5] = {1,4,4,5,7};
int n = 5;
int v = 10;
knap(w,v,n);
return 0;
}