
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.
1def knightDialer(n):
2 MOD = 10**9 + 7
3 moves = {0: [4, 6], 1: [6, 8], 2: [7, 9], 3: [4, 8],
4 4: [0, 3, 9], 5: [], 6: [0, 1, 7], 7: [2, 6],
5 8: [1, 3], 9: [2, 4]}
6
7 dp = [[0] * 10 for _ in range(n)]
8 for i in range(10):
9 dp[0][i] = 1
10
11 for i in range(1, n):
12 for j in range(10):
13 dp[i][j] = sum(dp[i - 1][m] for m in moves[j]) % MOD
14
15 return sum(dp[n - 1]) % MOD
16This function uses dynamic programming to calculate the number of valid phone numbers. The moves are stored in a dictionary with each digit pointing to its possible knight moves. We initialize a 2D list dp where dp[i][j] represents the number of numbers of length i+1 starting from digit j. The result is obtained by summing up 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.
1class Solution {
2 public
This Java implementation optimizes memory usage by replacing the 2D DP array with two 1D arrays representing the current and previous states. The prev array contains counts for numbers of length derived from the previous computations, updated iteratively in-place.