题目:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1
is read off as “one 1
” or 11
.
11
is read off as “two 1
s” or 21
.
21
is read off as “one 2
, then one 1
” or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
题目比较难懂,但理解题目之后就比较简单了。
- 首先,第一个数是
1
; - 第二个数
11
,表示前一个数1
有1
个1
; - 第三个数是
21
,表示前一个数11
有2
个1
; - 第四个数
1211
,表示前一个数21
有1
个2
,1
个1
; - … …
- 以此类推;
这是典型的递归。
- 终止条件n = 1
;
- 获得前一个字符串,然后遍历该字符串,对每个数字进行计数;
C++ 代码如下:
class Solution {
public:
string countAndSay(int n) {
if(n == 1)
{
return to_string(n);
}
string str = countAndSay(n-1);
int count = 1;
string newStr = "";
for(int i=0;i<str.size()-1;i++)
{
if(str[i] == str[i+1])
count++;
else
{
newStr += to_string(count) + str[i];
count = 1;
}
}
newStr += to_string(count)+str[str.size()-1];
return newStr;
}
};