Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
做了半天才发现人家要的是 1 这个 digit 的数量,不是 number 的数量, 又改了改,好歹是通过了, 但是代码确实丑。凑活看吧。
本来开始想用反向思维来解, 就是总数-所有不包含 1 的数字数量, 但是好像不太灵, 后来又发现是要 digit 的数量, 所以就彻底放弃直接用 dp 的方法来解 dp(i, reach_top, ones), i 代表第 i 位数字(从 0 开始), reach_top 代表前一位数字是不是已经达到最大值, ones 代表当前的 1 的数量。如果 reach_top = true, 那我们就只能从 0…=digits[i]中来挑选当前位的数字, 否则, 我们就可以从 0…=9 中选择。对于最后一位的处理同样要考虑 reach_top 和 ones, 具体的看代码吧
use std::collections::HashMap;
impl Solution {
fn rc(digits: &Vec<i32>, i: usize, reach_top: bool, ones: i32, cache: &mut HashMap<(usize, bool, i32), i32>) -> i32 {
let mut ans = 0;
// 如果是最后一位
if i == digits.len() - 1 {
// 如果上一位已经是最大
if reach_top {
// 如果前面的几位中已经包含1
if ones > 0 {
// 如果当前位为0, 将前面几位的1计入答案
if digits[i] == 0<