题目
You should implement a function that finds the N-th element in the Look-and-say sequence:
- 1,11,21,1211,111221,312211,13112221,11132132111,11,21,1211,111221,312211,13112221,1113213211
To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. For example:
- 11 is read off as "one 11" or 1111.
- 1111 is read off as "two 11s" or 2121.
- 2121 is read off as "one 22, then one 11" or 12111211.
- 12111211 is read off as "one 11, one 22, then two 11s" or 111221111221.
- 111221111221 is read off as "three 11s, two 22s, then one 11" or 312211312211.
Standard input
The template code reads on the first line a single integer NN.
Standard output
The template calls your functions and prints the returned result.
Input | Output |
---|---|
5 | 111221 |
10 | 13211311123113112211 |
题目分析
该Look-and-say序列从“1”开始,1可以读作“一个一”所以序列的下一个数据为“11”,11可以读作“两个一”所以序列的下一个数据为“21”(2表示个数,1表示数),以此类推......
要求输入一个整数N,输出序列里的第N个数据,例如:输入5,输出111221(序列里的第五个数)
那怎么解决这类问题呢?其实对于这个Look-and-say序列的规律是很明显的了,但是关键在于我们怎么用代码表示出这个规律,表示出来之后怎么满足输入输出的要求?这里很明显用递归是非常简单的,我们要找第N个数据,那么只需要找到它的前一个数据然后进行按规律变化就可以了,所以编写一个lookAndSay(int n)函数在里面递归lookAndSay(n-1)就可以了,最后返回得出的结果,这里建议用string类型比较简单
代码
#include<bits/stdc++.h>
using namespace std;
string lookAndSay(int n){
string s;
if(n==1){
return "1";
}
else{
s = lookAndSay(n-1);
string ans = "";
int count = 1;
for(int i=1;i<s.length();i++){
if(s[i]==s[i-1]){
count++;
}
else{
ans += to_string(count);
ans += s[i-1];
count = 1;
}
}
ans += to_string(count);
ans += s[s.length()-1];
return ans;
}
}
int main(){
int n;
cout<<"Enter the number of terms: ";
cin>>n;
cout<<lookAndSay(n);
return 0;
}
交流讨论
以上均为个人拙见,若有错误或者改进之处,欢迎评论区留言交流讨论