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裡。程式碼如下:
class Solution { public: string countAndSay(int n) { if (n <= 0) return ""; string res = "1"; while (--n) { string cur = ""; for (int i = 0; i < res.size(); ++i) { int cnt = 1; while (i + 1 < res.size() && res[i] == res[i + 1]) { ++cnt; ++i; } cur += to_string(cnt) + res[i]; } res = cur; } return res; } };
博主出於好奇列印出了前12個數字,發現一個很有意思的現象,不管列印到後面多少位,出現的數字只是由1,2和3組成,網上也有人發現了並分析了原因 (http://www.cnblogs.com/TenosDoIt/p/3776356.html),前十二個數字如下:
1 1 1 2 1 1 2 1 1 1 1 1 2 2 1 3 1 2 2 1 1 1 3 1 1 2 2 2 1 1 1 1 3 2 1 3 2 1 1 3 1 1 3 1 2 1 1 1 3 1 2 2 1 1 3 2 1 1 3 1 1 1 2 3 1 1 3 1 1 2 2 1 1 1 1 1 3 1 2 2 1 1 3 3 1 1 2 1 3 2 1 1 3 2 1 2 2 2 1 3 1 1 3 1 1 2 2 2 1 2 3 2 1 1 2 1 1 1 3 1 2 2 1 1 3 1 2 1 1 3 2 1 1
參考資料:
https://discuss.leetcode.com/topic/20195/c-solution-easy-understand