【leetcode】935. Knight Dialer
題目如下:
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
Note:
1 <= N <= 5000
解題思路:很明顯的動態規劃的場景。首先我們可以維護如下的一個對映字典key為到達的數字,value為可以由哪些數字經過一次跳躍到達key的數字。接下來假設dp[i][j] 為經過跳躍i次並且最後一次跳躍的終點是j,那麼有dp[i][j] = dp[i-1][dic[j][0]] + dp[i-1][dic[j][1]] + ... dp[i-1][dic[j][n]]。最終的結果就是dp[N][0] + dp[N][1] + ... dp[N][9]。後來經過測試發現,這種解法會超時,因為題目約定了N最大是5000,因此可以事先計算出1~5000的所有結果快取起來。
dic[1] = [6,8] dic[2] = [7,9] dic[3] = [4,8] dic[4] = [3,9,0] dic[5] = [] dic[6] = [1,7,0] dic[7] = [2,6] dic[8] = [1,3] dic[9] = [2,4] dic[0] = [4,6]
程式碼如下:
class Solution(object): res = [] def knightDialer(self, N): """ :type N: int :rtype: int """ if len(self.res) != 0: return self.res[N-1] dic = {} dic[1] = [6,8] dic[2] = [7,9] dic[3] = [4,8] dic[4] = [3,9,0] dic[5] = [] dic[6] = [1,7,0] dic[7] = [2,6] dic[8] = [1,3] dic[9] = [2,4] dic[0] = [4,6] dp = [] for i in range(5001): if i == 0: tl = [1] * 10 else: tl = [0] * 10 dp.append(tl) for i in range(5001): for j in range(10): for k in dic[j]: dp[i][j] += dp[i-1][k] for i in range(5001): self.res.append(sum(dp[i]) % (pow(10,9) + 7)) return self.res[N-1]