题解 | #统计每个月兔子的总数#
统计每个月兔子的总数
https://www.nowcoder.com/practice/1221ec77125d4370833fd3ad5ba72395
斐波那契数列,采用动态规划,兔子从第三个月开始,数量等于前两个月的数量之和,an = an-2+ an-1,解法如下:
import java.io.IOException; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int month = sc.nextInt(); int[] arr = new int[month]; arr[0] = 1; arr[1] = 1; if(month<3){ System.out.println(1); continue; } for(int i=2;i<month;i++){ arr[i] = arr[i-2] + arr[i-1]; } System.out.println(arr[month-1]); } } }