intf(string s, int min_sum, int max_sum){ int n = s.length(), memo[n][min(9 * n, max_sum) + 1]; memset(memo, -1, sizeof(memo)); // -1 表示没有计算过 function<int(int, int, bool)> f = [&](int i, int sum, bool is_limit) -> int { if (sum > max_sum) return0; // 非法数字 if (i == n) return sum >= min_sum; if (!is_limit && memo[i][sum] != -1) return memo[i][sum]; int res = 0; int up = is_limit ? s[i] - '0' : 9; for (int d = 0; d <= up; ++d) // 枚举要填入的数字 d res = (res + f(i + 1, sum + d, is_limit && d == up)) % MOD; if (!is_limit) memo[i][sum] = res; return res; }; returnf(0, 0, true); }
public: intcount(string num1, string num2, int min_sum, int max_sum){ int ans = f(num2, min_sum, max_sum) - f(num1, min_sum, max_sum) + MOD; // 避免负数 int sum = 0; for (char c: num1) sum += c - '0'; ans += min_sum <= sum && sum <= max_sum; // x=num1 是合法的,补回来 return ans % MOD; } };
funccount(num1, num2 string, minSum, maxSum int)int { const mod int = 1e9 + 7 f := func(s string)int { memo := make([][]int, len(s)) for i := range memo { memo[i] = make([]int, min(9*len(s), maxSum)+1) for j := range memo[i] { memo[i][j] = -1 } } var dfs func(p, sum int, limitUp bool)int dfs = func(p, sum int, limitUp bool) (res int) { if sum > maxSum { // 非法 return } if p == len(s) { if sum >= minSum { // 合法 return1 } return } if !limitUp { ptr := &memo[p][sum] if *ptr >= 0 { return *ptr } deferfunc() { *ptr = res }() } up := 9 if limitUp { up = int(s[p] - '0') } for d := 0; d <= up; d++ { // 枚举要填入的数字 d res = (res + dfs(p+1, sum+d, limitUp && d == up)) % mod } return } return dfs(0, 0, true) } ans := f(num2) - f(num1) + mod // 避免负数 sum := 0 for _, c := range num1 { sum += int(c - '0') } if minSum <= sum && sum <= maxSum { // x=num1 是合法的,补回来 ans++ } return ans % mod }
funcmin(a, b int)int { if b < a { return b }; return a }