题目描述
有n个数字,a[1],a[2],a[3]......a[n],以及一个数字m。
问n个数字中取出一些数字,这些数字的和能否等于m。
输入
多组测试数据,读入到文件尾结束。
第一行输入n,m。(1<=n<=20, 1<=m<=100)
第二行输入n个数字a[1],a[2],a[3]......a[n]。(1<=a[i]<=100)
输出
如果可以,输出YES,否则输出NO。
样例输入
5 5
1 1 1 1 1
5 5
2 2 2 2 2
样例输出
YES
NO
简单递归的运用
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int n,m;
int ans;
int a[111];
int b[111];
void fun(int x)
{
if(x==n+1)
{
int sum=0;
for(int i=1;i<=n;i++)
sum=sum+a[i]*b[i];
if(sum==m)
ans=1;
return;
}
b[x]=1;
fun(x+1);
b[x]=0;
fun(x+1);
}
int main()
{
while(cin>>n>>m&&n&&m)
{
ans=0;
b[0]=0;
for(int i=1;i<=n;i++)
cin>>a[i];
fun(1);
if(ans==1)
cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
递归的运用,
其实我本来就想用排序做的,
不过这种做法倒是给了好多的启示。