博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 935. Knight Dialer
阅读量:4621 次
发布时间:2019-06-09

本文共 1987 字,大约阅读时间需要 6 分钟。

原题链接在这里:

题目:

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: 1Output: 10

Example 2:

Input: 2Output: 20

Example 3:

Input: 3Output: 46

Note:

  • 1 <= N <= 5000

题解:

The question asks distinct numbers could dial.

It is actually the sum of ways jump ending at each cell.

Cell 1 could jump to cell 6 and 8. Thus accumlate the current ways count to next ways at 6 and 8.

Eventually, get all the sum.

Time Complexity: O(N).

Space: O(1).

AC Java: 

1 class Solution { 2     public int knightDialer(int N) { 3         if(N == 0){ 4             return 0; 5         } 6          7         if(N == 1){ 8             return 10; 9         }10         11         int M = 1000000007;12         long [] cur = new long[10];13         Arrays.fill(cur, 1);14         for(int k = 2; k<=N; k++){15             long [] next = new long[10];16 17             next[1] = (cur[6]+cur[8])%M;18             next[2] = (cur[7]+cur[9])%M;19             next[3] = (cur[4]+cur[8])%M;20             next[4] = (cur[3]+cur[9]+cur[0])%M;21             next[5] = 0;22             next[6] = (cur[1]+cur[7]+cur[0])%M;23             next[7] = (cur[2]+cur[6])%M;24             next[8] = (cur[1]+cur[3])%M;25             next[9] = (cur[2]+cur[4])%M;26             next[0] = (cur[4]+cur[6])%M;27             28             cur = next;29         }30         31         long res = 0;32         for(int i = 0; i<10; i++){33             res = (res + cur[i]) % M;34         }35         return (int)res;36     }37 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11480528.html

你可能感兴趣的文章
poj 1062 昂贵的聘礼 解题报告
查看>>
get the page name from url
查看>>
visual studio中csproj文件中的project guid改为小写 ( notepad++ 正则)
查看>>
TeeChart显示三维的图形,使用Surface
查看>>
如何使用 Idea 远程调试 Java 代码
查看>>
加密,解密
查看>>
在C#代码中应用Log4Net(一)简单使用Log4Net
查看>>
[转]如何写软件项目技术标
查看>>
每日站立会议个人博客五
查看>>
ddd
查看>>
死磕 java同步系列之AQS起篇
查看>>
利用Lucene把文本的字体格式进行改动,然后输出到一个新的文件里
查看>>
[Openstack] Expecting an auth URL via either --os-auth-url or env[OS_AUTH_URL]
查看>>
How to Create Modifiers Using the API QP_MODIFIERS_PUB.PROCESS_MODIFIERS
查看>>
待飞笔记(第一天 )
查看>>
解惑好文:移动端H5页面高清多屏适配方案
查看>>
traefik添加多证书
查看>>
PhantomJs 笔记
查看>>
js设计模式--语言类型
查看>>
C#多线程之二:ManualResetEvent和AutoResetEvent
查看>>