LintCode 1707: Knight Dialer (DP好题)

1707 · Knight Dialer

Algorithms

Medium

Accepted Rate44%

Description

Solution

Notes

Discuss

Leaderboard

Description

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.

1 \leq N \leq 50001≤N≤5000

Example

Example 1:

 
Input: 1
Output: 10
Explanation:
The answer may be 0, 1, 2, 3, ..., 9. 

Example 2:

 
Input: 2
Output: 20
Explanation:
The answer may be 04, 06, 16, 18, 27, 29, 34, 38, 43, 49, 40, 61, 67, 60, 72, 76, 81, 83, 94, 92.

Example 3:

 
Input: 3
Output: 46

Tags

Company

FacebookDropboxMicrosoftGoogle

解法1:DP。
dp[i][j]表示第i次跳到数字j时的distinct number数。
注意:
1) 1e+9之类的科学计数法默认是double。但如果我们定义成int M = 1e+9则可将其强转为int。注意1e+9仍在int范围内。
2) dp[1][i]初始化为1, 不是i。因为每个数字只能算一种情况。
3) unordered_set可以直接用vector<vector<int>>代替,因为序号0..9都是按顺序来的,可以当数组的索引。

class Solution {
public:
    /**
     * @param N: N
     * @return: return the number of distinct numbers can you dial in this manner mod 1e9+7
     */
    int knightDialer(int N) {
        //#define M (long long)(10e9 + 7)
        int M = 1e9 + 7;
        unordered_map<int, vector<int>> dict = 
        { {0, {4, 6}},
          {1, {6, 8}},
          {2, {7, 9}},
          {3, {4, 8}},
          {4, {0, 3, 9}},
          {5, {}},
          {6, {0, 1, 7}},
          {7, {2, 6}},
          {8, {1, 3}},
          {9, {2, 4}}   
        };

        vector<vector<int>> dp(N + 1, vector<int>(10, 0));
        for (int i = 0; i <= 9; i++) {
            dp[1][i] = 1;
        }
        
        for (int i = 2; i <= N; i++) {
            for (int j = 0; j <= 9; j++) {
                for (int k = 0; k < dict[j].size(); k++) {
                    dp[i][j] = (dp[i][j] + dp[i - 1][dict[j][k]]) % M;
                }
            }
        }
        int sum = 0;
        for (int i = 0; i <= 9; ++i) {
            sum = (sum + dp[N][i]) % M;
        }
        return sum;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值