1. 程式人生 > >LeetCode Problems 935

LeetCode Problems 935

2018/11/11

935. Knight Dialer

問題描述:

A chess knight can move as indicated in the chess diagram below: knight dialer This time, we place our chess knight on any numbered key of a phone pad (indicated above), and the knight makes N-1hops. 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

問題分析:

本題難度為Medium!屬於動態規劃問題,已給出的函式定義為

class
Solution: def knightDialer(self, N): """ :type N: int :rtype: int """

本題採取動態規劃演算法,每一步的電話數字與上一步的電話數字相關。nextNumbers本質上為一張查詢表,nextNumber[i]儲存了數字i下一步可以到達的數字;res[i]表示最後一步停留在數字i上的組合數(情況數),則sum(res)為最後輸出,每一步都更新新的結果res=newRes;newRes是在上一步res的基礎上當前這一步的結果。

程式碼實現:

#coding=utf-8
class Solution: def knightDialer(self, N): """ :type N: int :rtype: int """ #當前數字可以跳到的下一個數字,例:nextNumbers[0]=[4,6]表示0的可以跳到數字4或6 nextNumbers=[[4,6],[6,8],[7,9],[4,8],[3,9,0],[],[1,7,0],[2,6],[1,3],[2,4]] res = [1 for t in range(10)] #某一步數將走上其索引所在數字的所有情況的總數,初始化為第一步的結果 for i in range(1,N): #對於第i步 newRes = [0 for t in range(10)] #用來更新其總數情況。 for number in range(10): for j in nextNumbers[number]: newRes[j] += res[number] res = newRes return sum(res) % (10**9+7) #對輸出取模