问题基本描述:有一个背包,能盛放的物品总重量为S,设有N件物品,其重量分别为w1,w2,...wn,希望从N件物品中选择若干件物品,所选物品的重量之和恰能放入该背包,即所选物品的重量之和等于S。
递归算法
#include
<
stdio.h
>
#define N 7
#define S 15
int w[N + 1 ] = ... { 0,1,2,3,4,5,6,7} ;
int knap( int s, int n)
... {
if(s == 0)
return 1;
if(s < 0 || s >0 && n < 1)
return 0;
if(knap(s - w[n], n-1))
...{
printf("%4d ", w[n]);
#define N 7
#define S 15
int w[N + 1 ] = ... { 0,1,2,3,4,5,6,7} ;
int knap( int s, int n)
... {
if(s == 0)
return 1;
if(s < 0 || s >0 && n < 1)
return 0;
if(knap(s - w[n], n-1))
...{
printf("%4d ", w[n]);