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
1s"
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.
思路:递归
代码:
string countAndSay(int n) {
string res;
if(n<1)
return NULL;
else if(n == 1)
{
res="1";
return res;
}
else if(n == 2)
{
return "11";
}
int lenOfRes=0;
string s=countAndSay(n-1);
int len=s.length();
int count=1;
char temp;
int i=0;
for(i=0; i<len-1; ++i)
{
if(s[i] == s[i+1])
{
count++;
}
else
{
temp=count+48;
res+=temp;
res+=s[i];
count=1;
}
}
if(s[i-1] == s[i])
{
temp=count+48;
res+=temp;
res+=s[i];
}
if(s[i-1] != s[i])
{
temp=49;
res+=temp;
res+=s[i];
}
return res;
}