一道很easy的题,使用递归解决有33%的错误
望路过的大佬指点一二
代码如下:
#include <iostream>
#include <cstring>
using namespace std;
int A[6],B[10000];
int sum,ccount;
void dfs(int cur,int cursum,int digit)
{
if (cur == (digit % 2 ? (digit + 1) / 2 : digit / 2) &&cursum==sum)
{
int flag=0;
for (int j = 0; j < digit; j++)
{
flag = flag*10+A[j];
}
B[ccount++] = flag;
return;
}
if (cur > (digit % 2 ? (digit + 1) / 2 : digit / 2))
return;
int i;
cur == 0 ? i = 1 : i = 0;
for (; i <=9; i++)
{
A[cur] = A[digit-cur-1]=i;
if(cur== digit - cur - 1)
dfs(cur + 1, cursum + A[cur], digit);
else
dfs(cur + 1, cursum + 2*A[cur], digit);
}
}
int main()
{
cin >> sum;
ccount = 0;
dfs(0,0,5);
memset(A, 0, sizeof(A));
dfs(0, 0, 6);
if (ccount == 0)
{
cout << -1 << endl;
}
else
{
for (int i = 0; i < ccount; i++)
{
cout << B[i] << endl;
}
}
return 0;
}
无奈之下用了暴力:
代码如下:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int sum;
cin >> sum;
int flag=0;
for (int i = 1; i <= 9; i++)
{
for (int j = 0; j <= 9; j++)
{
for (int k = 0; k <= 9; k++)
{
if ((2 * i + 2 * j + k) == sum)
{
flag = 1;
cout << i << j << k << j << i << endl;
}
}
}
}
for (int i = 1; i <= 9; i++)
{
for (int j = 0; j <= 9; j++)
{
for (int k = 0; k <= 9; k++)
{
if ((2 * i + 2 * j + 2*k) == sum)
{
flag = 1;
cout << i << j << k << k << j << i << endl;
}
}
}
}
if (flag == 0)
cout << -1 << endl;
return 0;
}