Leetcode 38: Count and Say

本文介绍了一种使用递归算法来生成著名的看说(Look-and-say)数列的方法。该数列从数字1开始,后续每一项都是对前一项的描述。例如,1被读作“one 1”或11,11被读作“two 1s”或21,以此类推。代码中详细展示了如何通过递归函数计算任意指定项。

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

// 利用递归,需要注意最后一个数不能忘了加进去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.
class Solution {
public:
    string countAndSay(int n) {
        if(n == 1)
            return "1";
        else if (n == 2)
            return "11";
        else 
        {
            string result_pre = countAndSay(n-1);
            string result = "";
            char temp = result_pre[0];
            int count_pre = 1;
            for(int i=1; i<result_pre.length();i++)
            {
                if(temp == result_pre[i])
                    count_pre++;
                else
                {
                    result = result +  char(count_pre + '0') + temp;
                    count_pre = 1;                    
                }
                temp = result_pre[i];
            }
            result = result + char(count_pre + '0') + result_pre[result_pre.length()-1];
            return result;
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值