c++ - 代码运行但输入值后不显示输出
问题描述
我正在尝试使用向量在斐波那契数列上实现 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);
}
解决方案
这是更正后的代码。
#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
推荐阅读
- python - 计算值/字符串是否在python中按日期重复出现
- php - whereIn 仅从存储的数据 laravel 返回第一个值?
- flutter - 将progressDialog.shide()置于颤动中的问题
- python - 为什么此 format() 函数不起作用?
- angular - 如何在离子日期选择器组件中排除周末
- api - 在前端存储客户端提交的 API 密钥
- apache-spark - 为什么在流源中没有获得任何新偏移量的情况下触发了新批次?
- format - 如何为presto中的每三个整数数字格式化以逗号分隔的数字
- arrays - 类型错误:未定义不是函数('...props.items.map...'附近)
- excel - 使用 Excel VBA 将 Outlook 电子邮件从收件箱移动到基于主题行的存档子文件夹 (Outlook 365 - Microsoft Exchange)