//递归算法
#include<iostream>
using namespace std;
int a[1000];
int oil(int n, int m)
{
if (n == 0 || m < 0)
return 0;
else
{
if (m == a[n])
return 1;
else
{
if (oil(n - 1, m - a[n]) == 1)
return 1;
if (oil(n - 1, m) == 1)
return 1;
}
}
return 0;
}
int main()
{
int n, m;
while (cin >> n >> m)
{
int tatol = 0;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
tatol += a[i];
}
if (tatol < m || m==0)
printf("no\n");
else
{
if (oil(n, m))
printf("yes\n");
else
printf("no\n");
}
}
return 0;
}
//01背包
#include<algorithm>
#include<iostream>
using namespace std;
int dp[1000];
int main()
{
int n, m,a;
while (cin >> n >> m)
{
if (m == 0)
{
printf("no\n");
continue;
}
memset(dp, 0, sizeof(dp));
for (int i = 0; i < n; i++)
{
cin >> a;
for (int j = m; j >= a; j--)
dp[j] = max(dp[j], dp[j - a]+a);
}
printf("%s\n", dp[m] == m ? "yes" : "no");
}
}
//bool背包
利用01背包的思想
只要j-a为1则说明可以放,利用位运算 | 得到answer
#include<iostream>
using namespace std;
bool dp[1000];
int main()
{
int n, m,a;
while (cin >> n >> m)
{
if (m == 0)
{
printf("no\n");
continue;
}
memset(dp, 0, sizeof(dp));
dp[0] = 1;
for (int i = 0; i < n; i++)
{
cin >> a;
for (int j = m; j >= a; j--)
dp[j] = dp[j] | dp[j - a];
}
printf("%s\n", dp[m] ? "yes" : "no");
}
return 0;
}
//位运算
#include<iostream>
using namespace std;
int n, m;
int a[1000];
int main()
{
while (cin >> n >> m)
{
int tatol = 0;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
tatol += a[i];
}
if (tatol < m || m==0)
printf("no\n");
else
{
int t, t2 ;
int lim = 1 << n;
for (int i = 0; i < lim; i++)
{
t = 0, t2 = i;
for (int j = 1; i <= n; j++)
{
if (t2 & 1)
t += a[j];
t2 >>= 1;
}
if (t == m)
{
printf("yes\n");
return 0;
}
}
if (t != m)
{
printf("no\n");
}
}
}
return 0;
}