Leetcode 3704. Count No-Zero Pairs That Sum to N
- Leetcode 3704. Count No-Zero Pairs That Sum to N
- 1. 解题思路
- 2. 代码实现
- 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 1tgt = int(s[idx]) + 10 * rif tgt <= 1 and (not is_num1_empty) and (not is_num2_empty):return 0ans = 0for i in range(min(tgt+1, 10)):j = tgt-iif 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-iif 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 ansreturn dp(0, 0, True, True)
提交代码评测得到:耗时73ms,占用内存18.45MB。