外观数列


给定一个正整数 n,输出外观数列的第 n 项。

外观数列是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。你可以将其视作是由递归公式定义的数字字符串序列

  • countAndSay(1) = "1"
  • countAndSay(n) 是对 countAndSay(n-1) 的描述,然后转换成另一个数字字符串。

前五项如下:

1
2
3
4
5
6
7
8
9
10
1.     1
2. 11
3. 21
4. 1211
5. 111221
第一项是数字 1
描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 "11"
描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 "21"
描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 "1211"
描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 "111221"

要描述一个数字字符串,首先要将字符串分割为最小数量的组,每个组都由连续的最多相同字符组成。

对于每个组,先描述字符的数量然后描述字符,形成一个描述组。

  • 要将描述转换为数字字符串,先将每组中的字符数量用数字替换,再将所有描述组连接起来。
  • 例如,数字字符串 "3322251" 的描述如下图:

img

1.遍历上个字符串得到下个

遍历前一个字符串 得到后一个字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
void work(string &str, int cnt, char c) {
str += (char)(cnt + '0');//数字数量
str += c;//数字字符
}
void func(string &str1, string &str2) {
int cnt = 0;
for (int i = 0; i < str1.length(); ++i) {
if (cnt == 0 || str1[i] == str1[i - 1]) {
cnt++;
} else {
work(str2, cnt, str1[i - 1]);
cnt = 1;
}
}
work(str2, cnt, str1[str1.length() - 1]);
}
string countAndSay(int n) {
string ans[35] = {"", "1"};
for (int i = 2; i <= n; ++i) {
func(ans[i - 1], ans[i]);
}
return ans[n];
}
};

2.斐波那契数列求解思维优化

利用斐波那契数列求解的思维进行优化,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
void work(string &str, int cnt, char c) {
str += (char)(cnt + '0');//数字数量
str += c;//数字字符
}
void func(string &str1, string &str2) {
int cnt = 0;
for (int i = 0; i < str1.length(); ++i) {
if (cnt == 0 || str1[i] == str1[i - 1]) {
cnt++;
} else {
work(str2, cnt, str1[i - 1]);
cnt = 1;
}
}
work(str2, cnt, str1[str1.length() - 1]);
}
string countAndSay(int n) {
string ans[2] = {"", "1"};
int a = 0, b = 1;
for (int i = 2; i <= n; ++i) {
ans[a].clear();
func(ans[b], ans[a]);
swap(a, b);
}
return ans[b];
}
};