Files
python/C++专题课程/动态规划/动态规划-6-部分和问题.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

44 lines
999 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include<bits/stdc++.h>
using namespace std;
/*
知识点内容:部分和问题
文档内容参考:
https://www.cnblogs.com/aiguona/p/9218754.html
*/
int n, k, a[22], b[22];
bool dfs(int x, int sum) //从左到右遍历一遍可得解
{
if (sum > k)
return false;
if (x == n)
return sum == k; //如果前n项计算过了,返回sum=k是否相等
if (dfs(x + 1, sum)) {
b[x] = 0; //如果不加上a[x]的情况,标记为0;
return true;
}
if (dfs(x + 1, sum + a[x])) {
b[x] = 1; //如果加上a[x]的情况,标记为1;
return true;
}
return false;
}
int main() {
while (scanf("%d%d", &n, &k) != EOF) {
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
if (dfs(0, 0)) {
printf("YES\n");
for (int i = 0; i < n; i++)
if (b[i])
printf("%d ", a[i]);
printf("\n");
} else
printf("NO\n");
}
return 0;
}