leetcode 38
本题采用递归的方式解决,若采用空间换时间,时间还能在优化一下。
class Solution {
public:
string countAndSay(int n) {
if (n == 1)
{
return "1";
}
if (n == 2)
{
return "11";
}
string res_bf = countAndSay(n-1);
string res = "";
int cnt = 1;
int i;
for (i=1; i < res_bf.length(); i++)
{
if (res_bf[i] == res_bf[i-1])
{
cnt++;
}
else{
res.push_back(cnt + '0');
res.push_back(res_bf[i-1]);
cnt = 1;
}
}
res.push_back(cnt + '0');
res.push_back(res_bf[i-1]);
return res;
}
};