题目描述:
The count-and-say sequence is the sequence of integers with the first five terms as following:
- 1
- 11
- 21
- 1211
- 111221
1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.Note: Each term of the sequence of integers will be represented as a string.
找规律模拟的题,考逻辑。
class Solution {
public:
string countAndSay(int n) {
if(n==1)
return "1";
else
return iteration("1",1,n);
}
string iteration(string s,int k,int n){
//cout<<"k = "<<k<<" "<<"s = "<<s<<endl;
if(k==n)
return s;
string result;
int i,j;
for(i=0;i<s.size();){
j=i;
while(j<s.size()&&s[i]==s[j])
j++;
result.push_back(j-i+'0');
result.push_back(s[i]);
i=j;
//cout<<"result = "<<result<<endl;
}
return iteration(result,k+1,n);
}
};
本身是一个迭代的过程
本文介绍了一种基于逻辑模拟的方法来生成计数猜数序列的第n项。通过递归迭代的方式,从初始值1开始,逐步构建出完整的序列。每一步都详细记录了当前字符串的构成方式及其读法。
636

被折叠的 条评论
为什么被折叠?



