계단 오르기 문제-귀속과 동태 기획

제목.
한 사람이 계단을 오르면 그는 한 번에 한 단계 또는 두 단계를 걸을 수 있는데, 서로 다른 계단 수를 입력해서 몇 가지 다른 걷는 방법을 구할 수 있습니까?
샘플 입력
5 8 10
샘플 출력
8 34 89
세 가지 방법
import java.util.Scanner;

public class Main {
	public static int fun1(int n) {   //    
		if(n == 1 || n==0) {
			return 1;
		}
		return fun1(n-1) + fun1(n-2);
	}
	
	static int f[] = new int[100]; 
	public static int fun2(int n) {  //           
		if(n == 1 || n==0) {
			return 1;
		}
		if(f[n] != 0) {
			return f[n];
		}
		f[n] = fun2(n-1) + fun2(n-2);
		return f[n];
	}
	
	static int f1[] = new int[100];
	public static int fun3(int n) {
		f1[1] = 1;
		f1[0] = 1;
		for(int i = 2; i <= n; i++) {   //         
			f1[i] = f1[i-1] + f1[i-2];
		}
		return f1[n];
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		
		long start1 = System.currentTimeMillis();
		System.out.println( fun1(n));
		System.out.println(System.currentTimeMillis() - start1);
		
		long start2 = System.currentTimeMillis();
		System.out.println(fun2(n));
		System.out.println(System.currentTimeMillis() - start2);
		
		long start3 = System.currentTimeMillis();
		System.out.println(fun3(n));
		System.out.println(System.currentTimeMillis() - start3);
	}
	
}

좋은 웹페이지 즐겨찾기