Problem solution · C++

Count Good Integers on a Grid Path

Count Good Integers on a Grid Path: a C++ solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Dynamic programming
Source
Kamyu LeetCode Solutions
Length
239 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Count Good Integers on a Grid Path, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 239 lines of C++ from the credited upstream file count-good-integers-on-a-grid-path.cpp.
  • The implementation visibly relies on sequence storage, cached states.
  • 23 loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeCount Good Integers on a Grid Path · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(16 * 2 * 10 * 10)// Space: O(16 + 2 * 10) // dpclass Solution {public:    long long countGoodIntegersOnPath(long long l, long long r, string directions) {        static const int L = 16;         vector<bool> lookup(L);        const auto& count = [&](int64_t n) {            vector<int> digits(L);            for (int i = L - 1; i >= 0; --i) {                digits[i] = n % 10;                n /= 10;            }            int64_t dp[2][10] = {};            dp[1][0] = 1;            for (int i = 0; i < L; ++i) {                int64_t new_dp[2][10] = {};                for (int t = 0; t < 2; ++t) {                    const auto& bound = t ? digits[i] : 9;                    for (int k = 0; k < 10; ++k) {                        if (!dp[t][k]) {                            continue;                        }                        for (int d = 0; d <= bound; ++d) {                            int nk = k;                            if (lookup[i]) {                                if (d < k) {                                    continue;                                }                                nk = d;                            }                            new_dp[t && d == bound][nk] += dp[t][k];                        }                    }                }                for (int t = 0; t < 2; ++t) {                    for (int k = 0; k < 10; ++k) {                        dp[t][k] = new_dp[t][k];                    }                }            }            int64_t result = 0;            for (int t = 0; t < 2; ++t) {                for (int k = 0; k < 10; ++k) {                    result += dp[t][k];                }            }            return result;        };         int i = 0, j = 0;        lookup[i * 4 + j] = true;        for (const auto& x : directions) {            if (x == 'D') {                ++i;            } else {                ++j;            }            lookup[i * 4 + j] = true;        }        return count(r) - count(l - 1);    }}; // Time:  O(16 * 2 * 10 * 10)// Space: O(16 + 2 * 10)// dpclass Solution2 {public:    long long countGoodIntegersOnPath(long long l, long long r, string directions) {        static const int L = 16;         vector<bool> lookup(L);        const auto& count = [&](int64_t n) {            vector<int> digits(L);            for (int i = L - 1; i >= 0; --i) {                digits[i] = n % 10;                n /= 10;            }            vector<vector<int64_t>> dp(2, vector<int64_t>(10));            dp[1][0] = 1;            for (int i = 0; i < L; ++i) {                vector<vector<int64_t>> new_dp(2, vector<int64_t>(10));                for (int t = 0; t < 2; ++t) {                    const auto& bound = t ? digits[i] : 9;                    for (int k = 0; k < 10; ++k) {                        if (!dp[t][k]) {                            continue;                        }                        for (int d = 0; d <= bound; ++d) {                            int nk = k;                            if (lookup[i]) {                                if (d < k) {                                    continue;                                }                                nk = d;                            }                            new_dp[t && d == bound][nk] += dp[t][k];                        }                    }                }                dp = move(new_dp);            }            int64_t result = 0;            for (const auto& row : dp) {                result += accumulate(cbegin(row), cend(row), 0LL);            }            return result;        };         int i = 0, j = 0;        lookup[i * 4 + j] = true;        for (const auto& x : directions) {            if (x == 'D') {                ++i;            } else {                ++j;            }            lookup[i * 4 + j] = true;        }        return count(r) - count(l - 1);    }}; // Time:  O(16 * 2 * 10 * 10)// Space: O(16 * 10)// memoizationclass Solution3 {public:    long long countGoodIntegersOnPath(long long l, long long r, string directions) {        static const int L = 16;         const auto& count = [&](int64_t n) {            vector<bool> lookup(L);            vector<int> digits(L);            vector<vector<int64_t>> memo(L, vector<int64_t>(10, -1));            const auto memoization = [&](this auto&& memoization, int i, bool t, int k) -> int64_t {                if (i == 16) {                    return 1;                }                if (!t && memo[i][k] != -1) {                    return memo[i][k];                }                int64_t result = 0;                const auto& bound = t ? digits[i] : 9;                for (int d = 0; d <= bound; ++d) {                    int nk = k;                    if (lookup[i]) {                        if (d < k) {                            continue;                        }                        nk = d;                    }                    result += memoization(i + 1, t && (d == bound), nk);                }                if (!t) {                    memo[i][k] = result;                }                return result;            };                        for (int i = L - 1; i >= 0; --i) {                digits[i] = n % 10;                n /= 10;            }            int i = 0, j = 0;            lookup[i * 4 + j] = true;            for (const auto& x : directions) {                if (x == 'D') {                    ++i;                } else {                    ++j;                }                lookup[i * 4 + j] = true;            }            return memoization(0, true, 0);        };         return count(r) - count(l - 1);    }}; // Time:  O(16 * 2 * 10 * 10)// Space: O(16 * 2 * 10)// memoizationclass Solution4 {public:    long long countGoodIntegersOnPath(long long l, long long r, string directions) {        static const int L = 16;         const auto& count = [&](int64_t n) {            vector<bool> lookup(L);            vector<int> digits(L);            vector<vector<vector<int64_t>>> memo(L, vector<vector<int64_t>>(2, vector<int64_t>(10, -1)));            const auto memoization = [&](this auto&& memoization, int i, bool t, int k) -> int64_t {                if (i == 16) {                    return 1;                }                if (memo[i][t][k] == -1) {                    memo[i][t][k] = 0;                    const auto& bound = t ? digits[i] : 9;                    for (int d = 0; d <= bound; ++d) {                        int nk = k;                        if (lookup[i]) {                            if (d < k) {                                continue;                            }                            nk = d;                        }                        memo[i][t][k] += memoization(i + 1, t && (d == bound), nk);                    }                }                return memo[i][t][k];            };                        for (int i = L - 1; i >= 0; --i) {                digits[i] = n % 10;                n /= 10;            }            int i = 0, j = 0;            lookup[i * 4 + j] = true;            for (const auto& x : directions) {                if (x == 'D') {                    ++i;                } else {                    ++j;                }                lookup[i * 4 + j] = true;            }            return memoization(0, true, 0);        };         return count(r) - count(l - 1);    }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗