这道题只要看得懂题就没难度了。题目的意思大概就是,每个序列是上一个序列的报数。比如第四个序列1211就是第三个序列21的报数。这样就不难得知,如果知道序列n-1,遍历一下这个序列就能知道序列n了。
class Solution {
public:
string countAndSay(int n) {
vector<string> result;
result.push_back("");
result.push_back("1");
int num = 2;
while (num <= n) {
int l = result[num - 1].length();
char now = result[num - 1][0];
int count = 1;
string tmp = "";
for (int i = 1; i < l; i++) {
if (result[num - 1][i] == now) {
count++;
} else {
char count_c = count + '0';
tmp = tmp + count_c + now;
count = 1;
now = result[num - 1][i];
}
}
char count_c = count + '0';
result.push_back(tmp + count_c + now);
num++;
}
return result[n];
}
};