Time Limit: 3 s
Description
Given n numbers, your task is to insert '+' or '-' in front of each number to construct expressions. Note that the position of numbers can be also changed.
You can calculate a result for each expression. Please count the number of distinct results and output it.
Input
There are several cases.
For each test case, the first line contains an integer n (1 ≤ n ≤ 20), and the second line contains n integers a1,a2,
... ,an(-1,000,000,000 ≤ ai ≤ 1,000,000,000).
Output
For each test case, output one line with the number of distinct results
Sample Input
2
1 2
3
1 3 5
2
1 2
3
1 3 5
Sample Output
48
本题题意:
这题说的是第一行给你一个n,接下来一行给你n个数,可以在这n 个数前边加“+”或者“-”,计算这些数的和,输出有几种不同的和。
解题思路:
因为数据比较小,直接暴力深搜就可以。
代码:
#include <iostream>
#include <algorithm>
#include <map>
#include <cstdio>
using namespace std;
int a[25];
map <int,int> M;
int n,ans;
void dfs(int sum,int i)
{
if(i==n+1)
{
if(M[sum]==0)///如果没有出现过
{
M[sum]=1;
ans++;
}
return;
}
dfs(sum+a[i],i+1);
dfs(sum-a[i],i+1);
}
int main()
{
while(~scanf("%d",&n))
{
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
M.clear();
ans=0;
dfs(0,0);
printf("%d\n",ans);
}
return 0;
}