首页 > 解决方案 > 代码运行但输入值后不显示输出

问题描述

我正在尝试使用向量在斐波那契数列上实现 dp。如果我将备忘录全局声明为具有给定大小的数组,它运行良好。但是在使用向量时,它在控制台上没有显示输出。这里似乎有什么问题?

#include<bits/stdc++.h>
using namespace std;
int fib(int n)
{
    vector<int>memo;
    int f;
    if(memo[n]!=0)
        return memo[n];
    if(n<=2)
        return 1;
    else
        f = fib(n-1)+fib(n-2);
    memo.push_back(f);
    return f;

}

int main()
{
    int num;
    cin>>num;
    cout<<fib(num);
}

标签: c++

解决方案


这是更正后的代码。

#include <iostream>
#include <vector>

using namespace std;

int fib (int n)
{
    static vector<int>memo = {1, 1}; // should be static. also init it.
    int f;
    if (n < memo.size () && memo [n] != 0) // check the size of vector before accessing
        return memo [n];
    if (n <= 2)
        return 1;
    else
        f = fib (n - 2) + fib (n - 1); // n-2 should be found and inserted before n-1
    memo.push_back (f);
    return f;

}

int main ()
{
    int num;
    cin >> num;
    cout << fib (num);
}

代码存在三个主要问题。

  • 备忘录应该被声明为静态的。以前每次调用 fib() 时,它都会创建一个新的“备忘录”变量。

  • memo[n]!=0 可能会导致段错误,因为向量可能很小。您应该在引用第 n 项之前检查大小。

  • 您将第 n 个值推到第 (n-2) 个位置。所以我们先用 {1,1} 初始化向量

现在该系列将生成为... 1 1 2 5 8 13 21 34 55


推荐阅读