# The partial sum problem（DFS+减枝）

There are multiple test cases.
Each test case contains three lines.The first line is an integer N(1≤N≤20),represents the array contains N integers. The second line contains N integers,the ith integer represents A[i](-10^8≤A[i]≤10^8).The third line contains an integer K(-10^8≤K≤10^8).

If Tom can choose some integers from the array and their them is K,printf ”Of course,I can!”; other printf ”Sorry,I can’t!”.

 

4 1 2 4 7 13 4 1 2 4 7 15

 

Of course,I can! Sorry,I can't!

#include<iostream>
#include<stdio.h>
using namespace std;
int n,s,a[21],flag,i,j;
void dfs(int i, int sum)//传入位置与当前和s
{
if(i==n+1)
{
return ;
}
if(sum>s)
{
return ;//减枝
}
if(sum==s)
{
flag=1;
return ;
}
dfs(i+1,sum);
dfs(i+1,sum+a[i]);//对于第i+1个数取与不取
}
int main()
{
while (scanf("%d",&n)!=EOF)
{
flag=0;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&s);
dfs(0,0);
if(flag!=0)
{
printf("Of course,I can!\n");
}
else
{
printf("Sorry,I can't!\n");
}
}
return 0;
}//感觉DFS减枝与我之前写的递归没什么区别，但就是要超时，作为一个小白我暂时也很迷