0%

935. Knight Dialer

dp优化矩阵乘法 O(logn) time O(1) space
状态转移矩阵用column-based竖着看才行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
public:
int knightDialer(int N) {
vector<vector<long>> mtx = {
{0, 0, 0, 0, 1, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 1, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 0, 1},
{0, 0, 0, 0, 1, 0, 0, 0, 1, 0},
{1, 0, 0, 1, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 1, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 1, 0, 0, 0, 1, 0, 0, 0},
{0, 1, 0, 1, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 1, 0, 0, 0, 0, 0}
};
mtx = pow(mtx, N - 1);
vector<vector<long>> f{vector<long>(10, 1)};
f = mul(f, mtx);
int res = 0;
for (int i = 0; i < 10; ++i) {
res = (res + f[0][i]) % M;
}
return res;
}

vector<vector<long>> pow(vector<vector<long>> &mtx, int N) {
int n = mtx.size();
vector<vector<long>> res(n, vector<long>(n));
for (int i = 0; i < n; ++i) {
res[i][i] = 1;
}
while (N > 0) {
if (N & 1) {
res = mul(res, mtx);
}
mtx = mul(mtx, mtx);
N >>= 1;
}
return res;
}

vector<vector<long>> mul(const vector<vector<long>> &a, const vector<vector<long>> &b) {
int m = a.size(), n = b.size(), p = b[0].size();
vector<vector<long>> res(m, vector<long>(p));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < p; ++j) {
for (int k = 0; k < n; ++k) {
res[i][j] = (res[i][j] + a[i][k] * b[k][j]) % M;
}
}
}
return res;
}

int M = 1e9 + 7;
};

dp O(N) time O(1) space
bottom up
最底层是N=1每一层往上迭代累加即可
f[i]表示最后一个数为i的可能的拨号方式有多少种
f[i]表示当前层到最底层从i开始的不同number的个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int knightDialer(int N) {
vector<vector<int>> next = {{4, 6}, {6, 8}, {7, 9}, {4, 8}, {0, 3, 9}, {}, {0, 1, 7}, {2, 6}, {1, 3}, {2, 4}};
int M = 1e9 + 7;
vector<int> f(10, 1);
for (int i = 1; i < N; ++i) {
vector<int> t(10);
t.swap(f);
for (int u = 0; u < 10; ++u) {
for (int v : next[u]) {
f[v] = (f[v] + t[u]) % M;
}
}
}
int res = 0;
for (int i = 0; i < 10; ++i) {
res = (res + f[i]) % M;
}
return res;
}
};

dfs+memo O(N) time O(N) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int knightDialer(int N) {
next = {{4, 6}, {6, 8}, {7, 9}, {4, 8}, {0, 3, 9}, {}, {0, 1, 7}, {2, 6}, {1, 3}, {2, 4}};
m.resize(10, vector<int>(N + 1, -1));
int res = 0;
for (int i = 0; i < 10; ++i) {
res = (res + count(i, N)) % M;
}
return res;
}

int count(int u, int N) {
if (N == 1) return 1;
if (m[u][N] != -1) return m[u][N];
int res = 0;
for (int v : next[u]) {
res = (res + count(v, N - 1)) % M;
}
return m[u][N] = res;
}

int M = 1e9 + 7;
vector<vector<int>> m, next;
};