题目大意:
给出n个数,在这n个数两两之间加上加号或减号将其合并为一个数,求最终不同的结果的个数
代码如下:
#include <bits/stdc++.h>
using namespace std;
int n, a[22], s[5000], ans;
void dfs( int x, int t){
if ( x == n){
if ( !s[t + 2000]){
s[t + 2000] = 1;
ans++;
}
return;
}
dfs( x + 1, t + a[x]);
dfs( x + 1, t);
}
int main()
{
while ( ~scanf( "%d", &n)){
memset( s, 0, sizeof( s));
for ( int i = 0; i < n; i++){
scanf( "%d", &a[i]);
}
ans = 0;
dfs( 1, a[0]);
printf( "%d\n", ans);
}
return 0;
}
使用状态数组s保存最终和