
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.
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.