每日刷题(七十)
ALGO-139、s01串
递归法:
变换次数为0,则返回0,变化次数为1,则返回1,如果变化次数为2,那么就是01,我们可以大概猜想一个递归公式f(n) = f(n - 2) + f(n - 1)
接下来如果变换次数为3,则结果是101,那就是f(1) + f(2)的组合
接下来我们可以利用C++中string类型的拼接特点完成任务
详细C++代码如下:
#include<iostream>
using namespace std;
string f(int n)
{
if(n == 0)
return "0";
if(n == 1)
return "1";
else
return f(n - 2) + f(n - 1);
}
int main()
{
int n;
cin >> n;
cout << f(n) << endl;
return 0;
}
样例运行结果如下:
还有一种方法,思路更清晰,更容易找到的规律,但是代码量有点大
strcat法:
用两个数组,一个数组用来记录每次转换后的结果并作为最终结果输出,而另一个数组s2起到临时承载的作用。以s1长度来遍历s1的元素进行处理,s1如果为0,则s2就拼接上1,如果s1为1,s2就拼接上01,每次i的一轮循环结束后,就把s2的记录依次传给s1用来更新。之后s2再重新归为空
详细C++代码如下:
#include<iostream>
#include<cstring>
using namespace std;
char s1[30000] = {'0'};
int main()
{
int n;
cin >> n;
int i, j;
for(i = 0; i < n; i++)
{
char s2[30000] = {};
for(j = 0; j < strlen(s1); j++)
{
if(s1[j] == '0')
strcat(s2, "1");
else if(s1[j] == '1')
strcat(s2, "01");
}
for(j = 0; j < strlen(s2); j++)
{
s1[j] = s2[j];
}
}
s1[j + 1] = '\0';
cout << s1 << endl;
return 0;
}