首页 > 解决方案 > 斐波那契数列比奈矩阵的 C++ 实现

问题描述

对于以下代码,我收到此错误:没有已知的从 '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);
    }
}; 

标签: c++dynamic-programmingfibonacci

解决方案


您从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]}
        };
    }
};

推荐阅读