不死神兔java递归
时间: 2023-10-19 09:58:30 浏览: 95
对于不死神兔问题的Java递归实现,可以使用以下代码:
```java
public class CountRabbitNumber {
public static void main(String[] args) {
int month = 12;
int count = getCount(month);
System.out.println("第" + month + "个月兔子的对数是: " + count);
}
public static int getCount(int month) {
if (month == 1 || month == 2) {
return 1;
} else {
return getCount(month - 1) + getCount(month - 2);
}
}
}
```
在这个代码中,`getCount`方法使用递归的方式计算第n个月的兔子对数。如果n等于1或2,直接返回1。否则,返回第n-1个月和第n-2个月兔子对数的和。通过调用这个方法,可以得到第12个月的兔子对数。<em>1</em><em>2</em><em>3</em>
#### 引用[.reference_title]
- *1* *3* [Java 不死神兔的解决方法](https://blog.csdn.net/R813913/article/details/123465444)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}} ] [.reference_item]
- *2* [JAVA经典案例,不死神兔不用递归算法](https://blog.csdn.net/weixin_45842756/article/details/102963297)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}} ] [.reference_item]
[ .reference_list ]
阅读全文