小white刷题记——LeetCodeHot100_38

文章介绍了LeetCode第38题《外观数列》的解题思路,主要使用递归方法解决。当给定数n时,外观数列是通过观察前一层的序列生成的。例如,n=3的外观数列基于n=2的结果计算。代码中展示了C++的解决方案,包括递归函数countAndSay的实现和主函数的测试。
摘要由CSDN通过智能技术生成

LeetCodeHot100_38——《外观数列》

读题思路:

这道题一开始还没太看懂啥意思,但是结合例子来看一下就可以了,就是一个递归的方法,你想知道 n=3 的时候外观数列,就得先知道 n = 2 时的外观数列,因为 n=3 时的外观数列就是通过描述 n = 2 时的外观序列出来的。

具体代码:

#include<iostream>
#include<vector>
#include<string>

using namespace std;

string countAndSay(int n) {
    //先判断一下如果n=1的话,直接就可以返回1
    if (n == 1) { return "1"; }
    //然后定义一个空变量,用来存最后的答案
    else {
        string ans{};
        //这个时候就需要开始递归了
        //建立一个临时变量,用来存放没一层递归的答案
        string temp = countAndSay(n - 1);//递归迭代
        int length = temp.size();
        int count = 1;
        for (int i = 1; i <= length; i++)
        {
            if (temp[i] != temp[i - 1])//求每一次递归的观察队列
            {
                ans += count + '0'; //需要把count转换成char所以加了一个'0'
                ans += temp[i - 1];
                count = 0;
            }
            count++;
        }
        return ans;
    }
}

int main() {
    int n = 4;
    cout << countAndSay(n) << endl;
    return 0;
}

“ # 设置按钮的背景颜色 self.m_button1.SetBackgroundColour('#0a74f7') self.m_button1.SetForegroundColour('white') self.m_button2.SetBackgroundColour('#0a74f7') self.m_button2.SetForegroundColour('white') self.m_button3.SetBackgroundColour('#0a74f7') self.m_button3.SetForegroundColour('white') self.m_button4.SetBackgroundColour('#238E23') self.m_button4.SetForegroundColour('white') self.m_button5.SetBackgroundColour('#238E23') self.m_button5.SetForegroundColour('white') self.m_button6.SetBackgroundColour('#238E23') self.m_button6.SetForegroundColour('white') self.m_button7.SetBackgroundColour('#6F4242') self.m_button7.SetForegroundColour('white') self.m_button8.SetBackgroundColour('#6F4242') self.m_button8.SetForegroundColour('white') self.m_button9.SetBackgroundColour('#6F4242') self.m_button9.SetForegroundColour('white') self.m_button10.SetBackgroundColour('#8E6B23') self.m_button10.SetForegroundColour('white') self.m_button11.SetBackgroundColour('#8E6B23') self.m_button11.SetForegroundColour('white') self.m_button12.SetBackgroundColour('#8E6B23') self.m_button12.SetForegroundColour('white') self.m_button13.SetBackgroundColour('#8E6B23') self.m_button13.SetForegroundColour('white') self.m_button14.SetBackgroundColour('#545454') self.m_button14.SetForegroundColour('white') self.m_button15.SetBackgroundColour('#545454') self.m_button15.SetForegroundColour('white') self.m_button16.SetBackgroundColour('#545454') self.m_button16.SetForegroundColour('white') self.m_panel1.SetBackgroundColour('white') # 设置面板的背景颜色”逐行解释代码
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值