给出一个数字 N,打印交替的斐波那契数,直到第 n 个斐波那契。
例子:
Input : N = 7
Output : 0 1 3 8
Input : N = 15
Output : 0 1 3 8 21 55 144 377
阅读以下文章中的方法2 :斐波那契数
方法:使用动态规划方法。继续存储先前计算的斐波那契数,并使用前两个数存储下一个斐波那契数。
C++
// Alternate Fibonacci Series using Dynamic Programming
#include
using namespace std;
void alternateFib(int n)
{
if (n < 0)
return;
/* 0th and 1st number of the series are 0 and 1*/
int f1 = 0;
int f2 = 1;
cout << f1 << " ";
for (int i = 2; i <= n; i++) {
int f3 = f2 + f1;
if (i % 2 == 0)
cout << f3 << " ";
f1 = f2;
f2 = f3;
}
}
int main()
{
int N = 15;
alternateFib(N);
return 0;
}
Java
// Alternate Fibonacci Series
// using Dynamic Programming
import java.io.*;
class GFG
{
static void alternateFib(int n)
{
if (n < 0)
return;
/* 0th and 1st number of the
series are 0 and 1*/
int f1 = 0;
int f2 = 1;
System.out.print(f1 + " ");
for (int i = 2; i <= n; i++)
{
int f3 = f2 + f1;
if (i % 2 == 0)
System.out.print(f3 + " ");
f1 = f2;
f2 = f3;
}
}
// Driver Code
public static void main (String[] args)
{
int N = 15;
alternateFib(N);
}
}
// This code is contributed
// by chandan_jnu.
Python3
# Alternate Fibonacci Series
# using Dynamic Programming
def alternateFib(n):
if (n < 0):
return -1;
# 0th and 1st number of
# the series are 0 and 1
f1 = 0;
f2 = 1;
print(f1, end = " ");
for i in range(2, n + 1):
f3 = f2 + f1;
if (i % 2 == 0):
print(f3, end = " ");
f1 = f2;
f2 = f3;
# Driver Code
N = 15;
alternateFib(N);
# This code is contributed by mits
C#
// Alternate Fibonacci Series
// using Dynamic Programming
using System;
class GFG
{
static void alternateFib(int n)
{
if (n < 0)
return;
/* 0th and 1st number of
the series are 0 and 1*/
int f1 = 0;
int f2 = 1;
Console.Write(f1 + " ");
for (int i = 2; i <= n; i++)
{
int f3 = f2 + f1;
if (i % 2 == 0)
Console.Write(f3 + " ");
f1 = f2;
f2 = f3;
}
}
// Driver Code
public static void Main ()
{
int N = 15;
alternateFib(N);
}
}
// This code is contributed
// by chandan_jnu.
PHP
Javascript
输出:
0 1 3 8 21 55 144 377
时间复杂度: O(n)
辅助空间: O(1)