链接:acm.fafu.edu.cn/problem.php?id=1593
Description:
现给定一个含有n个元素的数组A,要求:从这n个数中选择一些数,这些数的和恰好为k
Input:
多组测试数据。第一行为n(1<=n<=20) 第二行为n个整数,每个数的范围为(-10^8≤A[i]≤10^8) 第三行为整数k(-10^8≤k≤10^8).
Output:
如果能够达到目的,输出”Of course,I can!”; 否则输出”Sorry,I can’t!”.
Sample Input:
4
1 2 4 7
13
4
1 2 4 7
15
Sample Output:
Of course,I can!
Sorry,I can't!
#include<cstdio>
int n,i,k,sum,YES;
int a[25],vis[25];
bool DFS(int i,int sum)
{
if(i < n && !vis[i])
{
vis[i] = 1; //走过,标记1
if(sum+a[i] == k)
return YES=1; //找到目标值
else if(sum+a[i] < k)
{
DFS(i+1,sum+a[i]);
DFS(i+1,sum); //sum加a[i]后继续往下找
//sum不加a[i]后继续往下找
}
else
DFS(i+1,sum); //不加a[i]继续找
vis[i] = 0; //回溯时取消标记
}
return YES;
}
int main(void)
{
while(~scanf("%d",&n))
{
for(i = 0; i < n; i++) //输入n个数字
scanf("%d",&a[i]);
scanf("%d",&k); YES = 0;//输入目标值k,初始化YES
for(i = 0; i < n; i++)
vis[i] = 0;//初始化vis数组
DFS(0,0);
if(YES) puts("Of course,I can!");
else puts("Sorry,I can't!");
}
return 0;
}