题目还是昨天的题,昨天已经介绍了三种解法了,今天介绍一个最快的方法。
题目链接
LeetCode 面试题 08.01. 三步问题[1]
示例1
输入:
n = 3
输出:
4
解释:
有四种走法
示例2
输入:
n = 5
输出:
13
代码
c++
typedef long long ll;
typedef vector<vector<ll>> vvl;
typedef vector<ll> vl;
const ll p = 1e9+7;
class Solution {
public:
vvl mat_mul(vvl& A, vvl& B) {
int a = A.size(), b = B.size(), c = B[0].size();
vvl C(a, vl(c, 0));
for (int i = 0; i < a; ++i) {
for (int j = 0; j < c; ++j) {
for (int k = 0; k < b; ++k) {
(C[i][j] += A[i][k] * B[k][j]) %= p;
}
}
}
return C;
}
vvl mat_pow(vvl& A, int n) {
int m = A.size();
vvl B(m, vl(m, 0));
for (int i = 0; i < m; ++i) B[i][i] = 1;
while (n > 0) {
if (n&1) B = mat_mul(B, A);
A = mat_mul(A, A);
n >>= 1;
}
return B;
}
vvl mat_pow_rec(vvl& A, int n) {
if (n == 1) return A;
vvl B = mat_pow_rec(A, n/2);
B = mat_mul(B, B);
if (n&1) return mat_mul(A, B);
return B;
}
int waysToStep(int n) {
vl f = {1, 2, 4};
if (n <= 3) return f[n-1];
vvl A = {{0, 0, 1}, {1, 0, 1}, {0, 1, 1}};
vvl B = mat_pow(A, n-3);
ll res = 0;
for (int i = 0; i < 3; ++i) {
(res += f[i] * B[i][2]) %= p;
}
return res;
}
};
python
import numpy as np
class Solution:
def mat_pow(self, A, n):
m = A.shape[0]
B = np.eye(m, dtype=np.int64)
while n > 0:
if (n&1)!=0:
B = np.mod(np.matmul(B, A), self.p).astype(np.int64)
A = np.mod(np.matmul(A, A), self.p).astype(np.int64)
n >>= 1
return B;
def waysToStep(self, n: int) -> int:
self.p = int(1e9+7)
f = [1, 2, 4]
if n <= 3: return f[n-1]
A = np.array([[0, 0, 1], [1, 0, 1], [0, 1, 1]], dtype=np.int64)
B = self.mat_pow(A, n-3)
res = 0
for i in range(3):
res += f[i] * B[i][2]
return int(res%self.p)
参考资料
[1]
LeetCode 面试题 08.01. 三步问题: https://leetcode-cn.com/problems/three-steps-problem-lcci/
[2]
韦阳的博客:【每日算法Day 79】所有人都会做的入门题,但是能看出你的代码能力!: https://godweiyang.com/2020/03/24/leetcode-inteview-08-01/
[3]
知乎专栏:【每日算法Day 79】所有人都会做的入门题,但是能看出你的代码能力!: https://zhuanlan.zhihu.com/p/115799226