
Sponsored
Sponsored
This approach uses dynamic programming to store and reuse the number of dialable numbers of length n starting from each digit. We maintain a 2D DP table where dp[i][j] indicates how many numbers of length i can start from digit j.
The primary idea is to iterate from i=1 to n, updating the DP table based on the moves possible from each digit in the previous state.
Time Complexity: O(n) for each of the 10 digits, resulting in O(10n) operations.
Space Complexity: O(10n) due to the DP table.
1#include <vector>
2using namespace std;
3
4class Solution {
5public:
6 int knightDialer(int n) {
7 constexpr int MOD = 1000000007;
8 vector<vector<int>> moves = {
9 {4, 6}, {6, 8}, {7, 9}, {4, 8}, {0, 3, 9},
10 {}, {0, 1, 7}, {2, 6}, {1, 3}, {2, 4}
11 };
12 vector<vector<int>> dp(n, vector<int>(10, 0));
13 for (int i = 0; i < 10; ++i) dp[0][i] = 1;
14
15 for (int i = 1; i < n; ++i) {
16 for (int j = 0; j < 10; ++j) {
17 for (int move : moves[j]) {
18 dp[i][j] = (dp[i][j] + dp[i - 1][move]) % MOD;
19 }
20 }
21 }
22
23 int result = 0;
24 for (int num : dp[n - 1]) {
25 result = (result + num) % MOD;
26 }
27
28 return result;
29 }
30};This C++ solution follows the same logic and dynamic programming approach as described. It uses a 2D vector dp to keep track of the number of possible numbers that can be formed with knight moves, starting from each digit. The final number of possible dialer numbers of length n is computed by summing the entries in the last row of dp.
This approach optimizes the dynamic programming technique by reducing space complexity. Instead of using a full 2D array, we use two 1D arrays to track only the current and the previous state, thus reducing the space required from O(n*10) to O(20).
Time Complexity: O(n) - iterating over digits with constant time calculations;
Space Complexity: O(10) as we only hold current and previous state arrays.
1def knightDialer(n):
2
This function uses a space-efficient dynamic programming approach. Instead of maintaining a 2D table, it uses two lists: prev and curr, which track the current and previous counts of numbers of length n. The prev list is updated at each step to effectively simulate the transition from i to i+1 without maintaining an entire history.