[英]How to print the fibonacci sequence in reverse order WITHOUT using a loop
我在接受采訪時得到了這個問題。 在面試官要我不使用我在打印方法中使用的循環時,這很容易。 術語數是一個輸入,當它是7時,例如:print 13 8 5 3 2 1 1.他說它在Python中很容易,但我也可以用Java編寫機制,但我想不出他可能是哪種機制提到。 謝謝!
我的Java代碼:
public class Fibonacci {
private int[] a;
private int fib(int i) {
assert (i>=0);
if (a[i]==0) {
if (i==0 || i==1) {
a[i] = 1;
} else {
a[i] = fib(i - 2) + fib(i - 1);
}
}
return a[i];
}
public Fibonacci(int numberTerms) {
if (numberTerms<2) throw new IllegalArgumentException("expect at least 2 terms for a Fibonacci sequence");
a = new int[numberTerms];
}
public void print() {
for (int i=a.length; i!=0; i--) {
System.out.println(fib(i-1));
}
}
public static void main(String[] args) {
Fibonacci f = new Fibonacci(7);
f.print();
}
}
public static int f(int n){
if (n <= 1)
return n;
else
return f(n-1) + f(n-2);
}
static void printReversedFib(int x){
if(x <= 1)
System.out.println(f(x));
else{
System.out.println(f(x));
printReverseFib(x-1);
}
}
用printReversedFib(7);
測試printReversedFib(7);
將打印:
13
8
5
3
2
1
1
據推測,你可以做一個遞歸print
; 就是這個 -
public void print() {
for (int i=a.length; i!=0; i--) {
System.out.println(fib(i-1));
}
}
可能是這樣的,
public void print() {
print(a.length - 1);
}
和
public void print(int i) {
if (i > 0) {
System.out.println(fib(i - 1));
print(i - 1);
}
}
當我運行上面的內容時,我得到了請求的輸出
13
8
5
3
2
1
1
我做了相反的方式。 誰能提升它? 歡迎所有建議。
package com.jbjares.dynamicProgramming;
public class Fibonacci {
public static void main(String[] args) {
new Fibonacci().calc(317811,1);
}
public void calc(Integer start,Integer end){
Integer f = (int) (start/((1+Math.sqrt(5))/2));
System.out.println(f);
if(f==end){
return;
}
calc(++f,end);
}
}
結果:196417 121393 75025 46368 28657 17711 10946 6765 4181 2584 1597 987 610 377 233 144 89 55 34 21 13 8 5 3 2 1
干杯!
您可以使用DP(動態程序)輕松解決此問題。您需要做的就是創建DP陣列,然后您可以按相反順序迭代陣列。 以下是Go中的解決方案。 http://play.golang.org/p/3m1n_AUSZl
func FibPrintRev(n int) {
space := make([]int, n+1)
// base case
space[1] = 1
space[2] = 1
// Create dp array
for i := 3; i <= n; i++ {
space[i] = space[i-1] + space[i-2]
}
// Iterate in rev. order
for i := n; i > 0; i-- {
fmt.Println(space[i])
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.