Fibonacci 系列的 Binet 矩阵的 C++ 实现
C++ implementation of Binet's matrices for Fibonacci series
对于以下代码,我收到此错误:第一个参数没有从 'int' 到 'const std::vector<std::vector<int, std::allocator >, std::allocator<std::vector<int, std::allocator > > >' 的已知转换。有人可以指出错误吗?
class Solution {
public:
int climbStairs(int n) {
vector<vector<int>>B{{1,1},
{1,0}};
for(int i=1;i<n;i++){
B=mult(B);
}
return(B[0][0]);
}
int mult(vector<vector<int>>B){
vector<vector<int>>ans{{0,0},
{0,0}};
ans[0][0]=B[0][0]+B[1][0];
ans[0][1]=B[0][1]+B[1][1];
ans[1][0]=B[0][0];
ans[1][1]=B[0][1];
return (vector<vector<int>>ans);
}
};
您从 mult
返回了错误的类型。您应该返回 std::vector<std::vector<int>>
,而不是 int
。
#include <vector>
class Solution {
public:
int climbStairs(int n) {
std::vector<std::vector<int>>B{{1, 1}, {1, 0}};
for(int i = 1; i < n; i++){
B = mult(B);
}
return B[0][0];
}
// pass by const& instead of value to avoid a copy here
std::vector<std::vector<int>> mult(const std::vector<std::vector<int>> &B) {
// simplify so that we don't need ans
return {
{B[0][0] + B[1][0], B[0][1] + B[1][1]},
{B[0][0], B[0][1]}
};
}
};
对于以下代码,我收到此错误:第一个参数没有从 'int' 到 'const std::vector<std::vector<int, std::allocator >, std::allocator<std::vector<int, std::allocator > > >' 的已知转换。有人可以指出错误吗?
class Solution {
public:
int climbStairs(int n) {
vector<vector<int>>B{{1,1},
{1,0}};
for(int i=1;i<n;i++){
B=mult(B);
}
return(B[0][0]);
}
int mult(vector<vector<int>>B){
vector<vector<int>>ans{{0,0},
{0,0}};
ans[0][0]=B[0][0]+B[1][0];
ans[0][1]=B[0][1]+B[1][1];
ans[1][0]=B[0][0];
ans[1][1]=B[0][1];
return (vector<vector<int>>ans);
}
};
您从 mult
返回了错误的类型。您应该返回 std::vector<std::vector<int>>
,而不是 int
。
#include <vector>
class Solution {
public:
int climbStairs(int n) {
std::vector<std::vector<int>>B{{1, 1}, {1, 0}};
for(int i = 1; i < n; i++){
B = mult(B);
}
return B[0][0];
}
// pass by const& instead of value to avoid a copy here
std::vector<std::vector<int>> mult(const std::vector<std::vector<int>> &B) {
// simplify so that we don't need ans
return {
{B[0][0] + B[1][0], B[0][1] + B[1][1]},
{B[0][0], B[0][1]}
};
}
};