LeetCodeHot100_38——《外观数列》
读题思路:
这道题一开始还没太看懂啥意思,但是结合例子来看一下就可以了,就是一个递归的方法,你想知道 n=3 的时候外观数列,就得先知道 n = 2 时的外观数列,因为 n=3 时的外观数列就是通过描述 n = 2 时的外观序列出来的。
具体代码:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
string countAndSay(int n) {
//先判断一下如果n=1的话,直接就可以返回1
if (n == 1) { return "1"; }
//然后定义一个空变量,用来存最后的答案
else {
string ans{};
//这个时候就需要开始递归了
//建立一个临时变量,用来存放没一层递归的答案
string temp = countAndSay(n - 1);//递归迭代
int length = temp.size();
int count = 1;
for (int i = 1; i <= length; i++)
{
if (temp[i] != temp[i - 1])//求每一次递归的观察队列
{
ans += count + '0'; //需要把count转换成char所以加了一个'0'
ans += temp[i - 1];
count = 0;
}
count++;
}
return ans;
}
}
int main() {
int n = 4;
cout << countAndSay(n) << endl;
return 0;
}