铺地板问题

铺地板问题_第1张图片

 

 

package com.henu;

import java.util.Scanner;

public class practice1 {
	//基于递归的实现,如果用else if会出现java.lang.StackOverflowError
	//栈溢出异常
	public static int diGui(int n) {		
		if(n == 0) {
			return 0;
		}
		if(n == 1){
			return 1;
		}
		if(n == 2) {
			return 2;
		}
		else {
			return diGui(n-1) + diGui(n-2);			
		}
	}
	//基于for循环的实现
	public static int For(int n) {
		int[] result = {0,1,2};
		if(n < 3) {
			return result[n];
		}
		int count1 = 1;
		int count2 = 2;
		int countn = 0;
		for (int i = 3; i <= n; i++) {
			countn = count1 + count2;
			count1 = count2;
			count2 = countn;
		}
		return countn;
	}
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		System.out.println(diGui(N));
		System.out.println(For(N));
	}

}

将其规律列出可以看出其规律为斐波那契。

你可能感兴趣的:(【JAVA】JAVA基础)