A chess knight can move as indicated in the chess diagram below:
.
This time, we place our chess knight on any numbered key of a phone pad (indicated above), and the knight makes N-1
hops. Each hop must be from one key to another numbered key.
Each time it lands on a key (including the initial placement of the knight), it presses the number of that key, pressing N
digits total.
How many distinct numbers can you dial in this manner?
Since the answer may be large, output the answer modulo 10^9 + 7
.
Example 1:
Input: 1 Output: 10
Example 2:
Input: 2 Output: 20
Example 3:
Input: 3 Output: 46
思路:这题就是状态之间的转换,dp[i] 由几个状态得来,然后初始都是1,然后走N步,最后就是所有dp[i]的总和,就是题目所求;
class Solution {
public int knightDialer(int n) {
int MOD = 1000000007;
int[] dp = new int[10];
Arrays.fill(dp, 1);
for(int i = 2; i <= n; i++) {
int[] dp_old = dp.clone();
dp[0] = (dp_old[4] + dp_old[6]) % MOD;
dp[1] = (dp_old[6] + dp_old[8]) % MOD;
dp[2] = (dp_old[7] + dp_old[9]) % MOD;
dp[3] = (dp_old[4] + dp_old[8]) % MOD;
dp[4] = ((dp_old[3] + dp_old[9]) % MOD + dp_old[0] % MOD) % MOD;
dp[5] = 0;
dp[6] = ((dp_old[1] + dp_old[7]) % MOD + dp_old[0] % MOD) % MOD;
dp[7] = (dp_old[2] + dp_old[6]) % MOD;
dp[8] = (dp_old[1] + dp_old[3]) % MOD;
dp[9] = (dp_old[2] + dp_old[4]) % MOD;
}
int res = 0;
for(int i = 0; i < dp.length; i++) {
res = (res % MOD + dp[i] % MOD) % MOD;
}
return res;
}
}