109th LeetCode Weekly Contest 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
说就是一个马在键盘上跳,能得到多少种的数字,比如1就是不跳。。在原地就是0到9,10个数
那么可以看看,0这个位置只有4和6可以跳过来,1是6,8可以跳过来,5是不可能到的,所以就有下面的代码(参考别人的,自己写的不好看)
class Solution { public: int mod = 1000000007; int dp[10],dp2[10]; int knightDialer(int N) { for(int i=0;i<=9;i++){ dp[i]=1; } for(int i=1;i<N;i++){ dp2[0] = (dp[4]+dp[6])%mod; dp2[1] = (dp[6]+dp[8])%mod; dp2[2] = (dp[7]+dp[9])%mod; dp2[3] = (dp[4]+dp[8])%mod; dp2[4] = ((dp[3]+dp[9])%mod+dp[0])%mod; dp2[5] = 0; dp2[6] = ((dp[1]+dp[7])%mod+dp[0])%mod; dp2[7] = (dp[2]+dp[6])%mod; dp2[8] = (dp[1]+dp[3])%mod; dp2[9] = (dp[2]+dp[4])%mod; for(int j=0;j<=9;j++){ dp[j] = dp2[j]; } } int result = 0; for(int i=0;i<=9;i++){ cout<<dp[i]<< " "; result += dp[i] %mod; result %= mod; } cout<<endl; return result; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~