
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.
1class Solution {
2 public int knightDialer(int n) {
3 int MOD = 1000000007;
4 int[][] moves = {
5 {4, 6}, {6, 8}, {7, 9}, {4, 8}, {0, 3, 9},
6 {}, {0, 1, 7}, {2, 6}, {1, 3}, {2, 4}
7 };
8
9 int[][] dp = new int[n][10];
10 for (int i = 0; i < 10; i++) dp[0][i] = 1;
11
12 for (int i = 1; i < n; i++) {
13 for (int j = 0; j < 10; j++) {
14 for (int move : moves[j]) {
15 dp[i][j] = (dp[i][j] + dp[i - 1][move]) % MOD;
16 }
17 }
18 }
19
20 int result = 0;
21 for (int num : dp[n - 1]) {
22 result = (result + num) % MOD;
23 }
24
25 return result;
26 }
27}This Java solution initializes a DP array where dp[i][j] holds the number of phone numbers of length i+1 starting at digit j. The nested loops fill in this DP table using the possible knight's moves defined for each digit. The final result is the sum of the values in the last row of the DP table.
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.
1#include <vector>
2#include <array>
3using namespace std;
4
class Solution {
public:
int knightDialer(int n) {
constexpr int MOD = 1000000007;
array<vector<int>, 10> moves = {
{{4, 6}}, {{6, 8}}, {{7, 9}}, {{4, 8}}, {{0, 3, 9}},
{}, {{0, 1, 7}}, {{2, 6}}, {{1, 3}}, {{2, 4}}
};
vector<int> prev(10, 1);
for (int i = 1; i < n; ++i) {
vector<int> curr(10, 0);
for (int j = 0; j < 10; ++j) {
for (int move : moves[j]) {
curr[j] = (curr[j] + prev[move]) % MOD;
}
}
prev = curr;
}
int result = 0;
for (int num : prev) {
result = (result + num) % MOD;
}
return result;
}
};The C++ code reduces space by using two single-dimensional arrays to store the current and previous numbers computed at each stage, instead of maintaining an entire DP table. This provides optimal space efficiency while retaining the same structure as multi-dimensional DP.