题目
思路①递归
把所有的数据都进行 + - 不操作三种情况,然后当把所有数据操作完之后,把和>0的情况变成1,最后输出即可
代码
#include<iostream>
#include<cstring>
using namespace std;
int yes[10000];
int data[100];
void re(int t, int sum)
{
if(t == -1)
{
if(sum > 0)
yes[sum] = 1;
return;
}
re(t - 1 , sum + data[t]);
re(t - 1 , sum - data[t]);
re(t - 1 , sum);
}
int main()
{
int t;
cin >> t;
int sum = 0;
memset(yes,0,sizeof(yes));
for(int i = 0; i < t; i++)
{
int temp;
cin >> temp;
data[i] = temp;
sum += temp;
}
re(t,0);
for(int i = 1; i <= sum; i++)
if(yes[i])
cout << "1";
else
cout << '0';
}
思路②dp
用个数组进行记录,但是数组没有负数的标号,所以我们不妨取中间段为0
(类似于计算机在记录浮点数记录幂次的时候0对应127,-1对应126一样)
没进行一个数据
f
(
1
,
a
1
)
=
1
f
(
1
,
−
a
1
)
=
1
f
(
1
,
0
)
=
1
f(1,a_1) = 1\quad f(1,-a_1)=1\quad f(1,0)=1
f(1,a1)=1f(1,−a1)=1f(1,0)=1
f ( 2 , a 1 + a 2 ) = 1 f ( 2 , − a 1 + a 2 ) = 1 f ( 2 , a 2 ) = 1 f ( 2 , a 1 − a 2 ) = 1 f ( 2 , − a 1 − a 2 ) = 1 f ( 2 , − a 2 ) = 1 f ( 2 , − a 2 ) = 1 f ( 2 , + a 2 ) = 1 f ( 2 , 0 ) = 1 f(2,a_1+a_2) = 1\quad f(2,-a_1+a_2)=1\quad f(2,a_2)=1\quad f(2,a_1-a_2) = 1\quad f(2,-a_1-a_2)=1\quad f(2,-a_2)=1\quad f(2,-a_2) = 1\quad f(2,+a_2)=1\quad f(2,0)=1 f(2,a1+a2)=1f(2,−a1+a2)=1f(2,a2)=1f(2,a1−a2)=1f(2,−a1−a2)=1f(2,−a2)=1f(2,−a2)=1f(2,+a2)=1f(2,0)=1
代码
#include<iostream>
#include<string.h>
using namespace std;
int yes[100][10000];
int data[100];
int main()
{
int t;
cin >> t;
int sum = 0;
for(int i = 0; i < t; i++)
{
int temp;
cin >> temp;
data[i] = temp;
sum += temp;
}
memset(yes, 0 ,sizeof(yes));
yes[0][5000] = 1;
for(int i = 1; i <= t; i++)
{
for(int j = 0; j < 10000; j++)
{
if(yes[i - 1][j])
{
yes[i][j]++;
yes[i][j + data[i - 1]]++;
yes[i][j - data[i - 1]]++;
}
}
}
for(int i = 5001; i <= 5000 + sum; i++)
cout << ((yes[t][i]) ? '1' : '0');//
}