给定n个不同的正整数集合w=(w1,w2,…,wn)和一个正数W,要求找出w的子集s,使该子集中所有元素的和为W。
输入格式:
第一行输入n和W,第二行依次输入n个数。
输出格式:
每行输出一个符合要求的子集。
输入样例1:
4 31
11 13 24 7
输出样例1:
11 13 7
24 7
源代码
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int arr[100];
//保存选了哪个,方便最后输出
bool flag[100];
//当前的累加值
int present_value=0;
int n,sum;
//用来判断有没有最终的解
bool isHasFinal=false;
//递归回溯
void find_sum(int i)
{
//因为我的输入是从0 开始的,所以== 就可以了,如果输入是数组下标1开始的
//则需要i>n来判定
if(i==n) return;
flag[i]=true;
present_value+=arr[i];
if(present_value == sum)
{
for(int j=0;j<n;j++)
{
if(flag[j])
{
cout<<arr[j]<<" ";
}
}
isHasFinal=true;
cout<<endl;
}
else if(present_value<sum)
{
find_sum(i+1);
}
//回溯
flag[i]=false;
present_value-=arr[i];
find_sum(i+1);
return;
}
int main()
{
cin>>n>>sum;
memset(flag,0,sizeof(flag));
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
find_sum(0);
if(!isHasFinal)
{
cout<<"No Solution!";
}
return 0;
}
运行截图: