Leetcode 3704. Count No-Zero Pairs That Sum to N

1. 解题思路

这一题思路上就是一个动态规划的思路,我们只需要考虑每一位上两个数各自取什么非零的位数即可。

唯一需要注意的是,需要注意一下余数以及开头为0的情况即可。

2. 代码实现

给出python代码实现如下:

class Solution:
    def countNoZeroPairs(self, n: int) -> int:
        s = str(n)
        l = len(s)

        @lru_cache(None)
        def dp(idx, r, is_num1_empty, is_num2_empty):
            if idx >= l:
                return 0 if (r != 0 or is_num1_empty or is_num2_empty) else 1
            tgt = int(s[idx]) + 10 * r
            if tgt <= 1 and (not is_num1_empty) and (not is_num2_empty):
                return 0
            ans = 0
            for i in range(min(tgt+1, 10)):
                j = tgt-i
                if 0 < i < 10 and 0 < j < 10:
                    ans += dp(idx+1, 0, False, False)
                elif is_num1_empty and i == 0 and 0 < j < 10:
                    ans += dp(idx+1, 0, True, False)
                elif is_num2_empty and j == 0 and 0 < i < 10:
                    ans += dp(idx+1, 0, False, True)

                j = tgt-1-i
                if 0 < i < 10 and 0 < j < 10:
                    ans += dp(idx+1, 1, False, False)
                elif is_num1_empty and i == 0 and 0 < j < 10:
                    ans += dp(idx+1, 1, True, False)
                elif is_num2_empty and j == 0 and 0 < i < 10:
                    ans += dp(idx+1, 1, False, True)
                elif is_num1_empty and is_num2_empty and i == 0 and j == 0:
                    ans += dp(idx+1, 1, True, True)
            return ans
        
        return dp(0, 0, True, True)

提交代码评测得到:耗时73ms,占用内存18.45MB。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值