Count and Say

本文介绍了如何通过递归和迭代两种方法实现计数并说出序列的生成算法。该序列从1开始,后续每一项都是对其前一项的描述。文中提供了详细的代码实现及解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目: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(n),就是根据string(n-1)进行求解,所以使用了迭代的方法。

真正开始判断的时候,定义一个count和一个初始的位置,这种方法已经不止一次的遇到!!!

只要是相同,那么就下一个,并且count加1,如果不同先是插入几个不同的数字,再插入原来的字符。

但是要注意最后的一个字符。

还有一个思路没有看。也贴上来。


代码:

class Solution {
public:
//https://leetcode.com/problems/count-and-say/
string countAndSay(int n) {
    //return solution1(n);        //recursive
    return solution2(n);        //iterative
}
private:
string solution1(int n){
    if(n == 2) return "11";
    if(n == 1) return "1";
    string s = solution1(n - 1);
    int count = 1, i;
    char c = s[0];
    string ns;
    for(i = 1; i < s.length(); i++){
        if(s[i] == c) count++;
        else{
            ns += char('0'+count);
            ns += c;
            c = s[i];
            count = 1;
        }
    }
    if(i == s.length()){
        ns += char('0'+count);
        ns += c;
    }
    return ns;

}
string solution2(int n){
    if(n-- == 1) return "1";
    string cur, pre = "11";
    while(--n){
        int count = 1, i;
        char c = pre[0];
        for(i = 1; i < pre.length(); i++){
            if(pre[i] == c) count++;
            else{
                cur += char('0'+count);
                cur += c;
                c = pre[i];
                count = 1;
            }
        }
        if(i == pre.length()){
            cur += char('0'+count);
            cur += c;
        }
        pre = cur;
        cur = "";
    }
    return pre;
}
};


转载于:https://www.cnblogs.com/jsrgfjz/p/8519904.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值