java面試:兔子問題

來源:互聯網
上載者:User

解決這個問題要注意:找到遞迴方法體,遞迴出口。

package com.cc; /**
 * 
 *  有一對兔子,從出生後第三個月起每個月都生一對兔子,小兔子長到第三個月後每個月又生一對兔子,假如兔子都不死,問每個月兔子總數是多少。
 * @author liukeqing
 *
 */
public class Hello {

public static void main(String[] args) {
int month = 8;//第幾個月
int sum = getCount(month);//擷取這個月兔子的總數
System.out.println("第"+month+"個月生兔子 : "+sum +"只");
}
//遞迴演算法的設計思路:對於一個複雜的問題,把原問題分解為若干個相對簡單雷同的子問題。繼續下去直到子問題簡單到能夠直接求解。
/**
* 擷取第n月兔子總數=老兔子總數 + 新生的兔子總數 = 上個月(n-1)的兔子總數 + 上上個月(n-2)的兔子總數
* @param month 第幾個月
* @return
*/
private static int getCount(int month){
int sum = 0;//每月兔子總數
if(month == 1 || month ==2){//每對兔子的第一個月和第二個月都不生育,兔子都是一對
sum = 2;
}else{//兔子開始生育
sum = getCount(month - 1) + getCount(month - 2);
}
return sum;
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.