// 利用递归,需要注意最后一个数不能忘了加进去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
.
class Solution {
public:
string countAndSay(int n) {
if(n == 1)
return "1";
else if (n == 2)
return "11";
else
{
string result_pre = countAndSay(n-1);
string result = "";
char temp = result_pre[0];
int count_pre = 1;
for(int i=1; i<result_pre.length();i++)
{
if(temp == result_pre[i])
count_pre++;
else
{
result = result + char(count_pre + '0') + temp;
count_pre = 1;
}
temp = result_pre[i];
}
result = result + char(count_pre + '0') + result_pre[result_pre.length()-1];
return result;
}
}
};