2021/4/8 剑指 Offer 17. 打印从1到最大的n位数(大数道理懂了 还没写过)

124 篇文章 1 订阅
53 篇文章 0 订阅
该博客介绍了如何使用递归全排列的方法解决LeetCode中的一个题目,即打印从1到最大的n位数。博主提供了两种解法,一种是简单的循环生成法,另一种是递归全排列实现,特别强调了递归全排列的执行机制。文章通过实例解释了代码逻辑,并给出了完整的C++代码实现。
摘要由CSDN通过智能技术生成

https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/solution/fei-zi-jie-ti-ku-jian-17-jian-dan-da-yin-cong-1dao/
这个多看看 讲的还行吧

力扣把他当简单题了 所以应该没有考虑大数问题:(常规解法 面试不能)

class Solution {
public:
    vector<int> printNumbers(int n) {
        int max=1;
        for(int count=1;count<=n;count++){
            max=max*10;//最大数
        }
        vector<int> result;
        for(int i=1;i<max;i++){
            result.push_back(i);
        }
        return result;
    }
};

递归全排列解法:
假设 n = 3,要输出的数其实就是三位数的全排列(000,001,002,…,999,当然 000 不能输出),我们用递归来表示出这个过程即可。

class Solution {
public:
    vector<int> output;
    vector<int> printNumbers(int n) {
        if(n <= 0) return vector<int>(0);
        string s(n, '0');
        for(int i=0; i<=9; ++i)
        {
            s[0] = i + '0';
            permutation(s, s.length(), 1);
        }
        return output;
    }
    void permutation(string& s, int length, int pos)
    {
        // 这个函数的执行机制我想了好久才弄明白,mark一下,对带有循环的递归有时候还挺绕的
        if(pos == length)
        {
           inputNumbers(s);
           return; 
        }
        for(int i=0; i<=9; ++i)
        {
            s[pos] = i + '0';
            permutation(s, length, pos + 1);
        }
    }
    void inputNumbers(string s)
    {
		//本函数用于循环往output中添加符合传统阅读习惯的元素。比如001,我们会添加1而不是001。
        bool isUnwantedZero = true;
        string temp = "";
        for(int i=0; i<s.length(); ++i)
        {
            if(isUnwantedZero && s[i] != '0') isUnwantedZero = false;
            if(!isUnwantedZero) temp += s[i];
        }
        if(temp != "") output.push_back(stoi(temp)); // 如果 s = "000",则temp会是空,stoi无法执行,会报错
    }
};

作者:superkakayong
链接:https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/solution/fei-zi-jie-ti-ku-jian-17-jian-dan-da-yin-cong-1dao/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值