Skip to content

Commit d4d1ed7

Browse files
committed
Runtime: 48 ms (Top 81.41%) | Memory: 8.50 MB (Top 76.13%)
1 parent a18a64f commit d4d1ed7

File tree

1 file changed

+37
-14
lines changed

1 file changed

+37
-14
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,42 @@
1-
// Runtime: 0 ms (Top 100.00%) | Memory: 6 MB (Top 96.62%)
1+
// Runtime: 48 ms (Top 81.41%) | Memory: 8.50 MB (Top 76.13%)
2+
23
class Solution {
3-
int MOD=1e9+7;
44
public:
5+
static const int mod = 1e9 + 7;
6+
vector<vector<int>> MOVES = {
7+
{4, 6},
8+
{8, 6},
9+
{7, 9},
10+
{4, 8},
11+
{3, 9, 0},
12+
{},
13+
{0, 1, 7},
14+
{2, 6},
15+
{1, 3},
16+
{2, 4},
17+
};
18+
19+
int cache[5001][10];
20+
521
int knightDialer(int n) {
6-
if(n==1) return 10;
7-
int a=2, b=2, c=3, d=2; //a{2,8} b{1,3,7,9} c{4,6} d{0}
8-
for(int i=3; i<=n; i++){
9-
int w, x, y, z;
10-
w = 2ll*b%MOD;
11-
x = (1ll*a + 1ll*c)%MOD;
12-
y = (2ll*b + 1ll*d)%MOD;
13-
z = 2ll*c%MOD;
14-
a = w; b = x; c = y; d = z;
22+
vector<int> nextNumbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
23+
return knightDialer(n, nextNumbers);
24+
}
25+
26+
int knightDialer(int remaining, vector<int>& nextNumbers) {
27+
if (remaining == 1)
28+
return nextNumbers.size();
29+
30+
int count = 0;
31+
for (int nextNumber : nextNumbers) {
32+
int cur = cache[remaining][nextNumber];
33+
if (cur == 0) {
34+
cur = knightDialer(remaining - 1, MOVES[nextNumber]);
35+
cache[remaining][nextNumber] = cur;
36+
}
37+
count += cur;
38+
count %= mod;
1539
}
16-
int ans = (2ll*a + 4ll*b + 2ll*c + d)%MOD;
17-
return ans;
40+
return count;
1841
}
19-
};
42+
};

0 commit comments

Comments
 (0)