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
Sample Output
4 8
其实就是一个递归啦,别想太多啦,迷迷糊糊就能过
#include <iostream>
#include <set>
using namespace std;
int a[25];
set <int> q;
void getsum(int sum,int n,int m){
if(n == m){
q.insert(sum);
return;
}
getsum(sum+a[n],n+1,m);
getsum(sum-a[n],n+1,m);
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
for(int i = 0;i < n; i++){
scanf("%d",&a[i]);
}
q.clear();
getsum(0,0,n);
int u = q.size();
printf("%d\n",u);
}
}