LeetCode 902. 最大为 N 的数字组合*

这篇博客介绍了如何利用深度优先搜索(DFS)算法解决一个数学问题,即在给定特定数字集合的情况下,计算能组成的所有非降序数列的数量。博客中详细展示了边界条件判断的难点,并提供了完整的C++代码实现,包括`shallow_cnt`函数用于计算组合计数,以及`digit_cnt`函数用于递归地计算数字集合的计数。
摘要由CSDN通过智能技术生成

具体思想:

dfs就可以,但是坑在边界判定上,有点繁琐;

具体代码:

class Solution {
public:
    int atMostNGivenDigitSet(vector<string>& digits, int n) {
        int cnt=0;
        string s="";
        while(n!=0){
            s.insert(s.begin(),'0'+n%10);
            n/=10;
        }
        cnt+=shallow_cnt(digits.size(),s.size()-1);
        cnt+=digit_cnt(digits,s,0);
        return cnt;
    }

    int shallow_cnt(int m,int n){
        int cnt=0;
        while(n!=0){
            cnt+=pow(m,n);
            n--;
        }
        return cnt;
    }


    int digit_cnt(vector<string>& digits,string& s,int index){
        if(index==s.size())
            return 1;
        int cnt=0;
        int top_dight=s[index]-'0';
        for(int i=0;i<digits.size();i++){
            int num=digits[i][0]-'0';
            if(num<top_dight){
                cnt+=pow(digits.size(),s.size()-1-index);
            }else if(num==top_dight){
                int res=1;
                res*=digit_cnt(digits, s, index+1);
                cnt+=res;
            }
        }
        return cnt;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值