「外觀數列」是一個整數序列,從數字 1 開始,序列中的每一項都是對前一項的描述。前五項如下:
1->1
2->11
3->21
4->1211
5->111221
2中的11表示前一個序列1是由1個1表示的;3中的21表示2中的11是由2個1表示的,依次類推;
解題思路:使用遞歸,要求第n個整數的輸出,需要知道第n-1個數的序列,要知道第n-1個數的序列,需要知道第n-2個數的序列,以此類推,直到n=1,返回’1’。
具體解題代碼如下:
# Python3
class Solution:
def countAndSay(self, n: int) -> str:
if n == 1:
return "1"
string = self.countAndSay(n-1) # 使用遞歸
ans = ""
nums = 1
temp = string[0]
for s in string[1:]:
if s == temp:
nums += 1
else:
ans += (str(nums) + str(temp))
temp = s
nums = 1
ans += (str(nums) + str(temp))
return ans
# C++
class Solution {
public:
string countAndSay(int n) {
if (n == 1)
return "1";
string strs = countAndSay(n-1);
int length = strs.size();
int nums = 1;
char temp = strs[0];
string ans = "";
for(int i=1;i<length;++i)
{
if(strs[i]!=temp)
{
ans += ('0'+nums);
ans += temp;
temp = strs[i];
nums = 1;
}
else
nums += 1;
}
ans += ('0'+nums);
ans += temp;
return ans;
}
};