题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=1058
题目解析:01背包的思想,对于每个数选择取或不取,然后用栈保存沿途的数。
代码如下:
01.
#include<cstdio>
02.
#include<cstring>
03.
#include<stack>
04.
using
namespace
std;
05.
int
n,k;
06.
int
f[23];
07.
stack<
int
>s;
//用栈保存需要用到的数
08.
bool
dfs(
int
i,
int
sum)
//一个用来代表所选数的个数,一个代表当前得到的和
09.
{
10.
if
(i==n)
11.
{
12.
if
(sum==k)
return
true
;
13.
return
false
;
14.
}
15.
if
(dfs(i+1,sum))
return
true
;
//不取当前数字
16.
if
(dfs(i+1,sum+f[i]))
17.
{
18.
s.push(f[i]);
19.
return
true
;
20.
}
21.
}
22.
int
main()
23.
{
24.
while
(
scanf
(
"%d%d"
,&n,&k)!=EOF)
25.
{
26.
for
(
int
i=0;i<n;i++)
27.
scanf
(
"%d"
,&f[i]);
28.
if
(dfs(0,0))
29.
{
30.
printf
(
"YES\n"
);
31.
while
(!s.empty())
32.
{
33.
printf
(
"%d "
,s.top());
34.
s.pop();
35.
}
36.
printf
(
"\n"
);
37.
}
38.
else
39.
printf
(
"NO\n"
);
40.
}
41.
return
0;
42.
}