1. 程式人生 > >爬樓梯演算法問題分析(不止三步)

爬樓梯演算法問題分析(不止三步)

演算法分析:

  1. 階梯數為1,爬樓梯方法就一種,為1,f(1)=1;
  2. 階梯數大於1的時候,遞迴求解:階梯數為2的時候,最多兩種方式上樓:1 ,1;2  =>  f(2)=2;
  3. 爬三層樓梯的時候,爬1層,再爬兩層,則是爬三層樓梯由爬一層樓梯和爬兩層樓梯的情況的結合:f(3)=f(2)+f(1);
  4. 以此類推:f(n) = f(n-1)+f(n-2)+...+f(n-n+1)   =>   f(n)=f(n-1)+f(n-2)+...+f(1);此種情況,設定的最大爬階梯數為n-1;
  5. 當限定最大爬階梯數量為m時候(0 ≤ m ≤ n-1) 那麼,f(n)=f(n-1)+f(n-2)+...+f(n-m)。
 /**
  * 
  */
package com.cn.count;


import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;


import javax.swing.JFrame;


/**
 * 
 * 演算法-爬樓梯問題
 * 
 * @author ymf
 * 
 */
public class Count extends JFrame{

	/**
	 * main方法
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Count cout = new Count();
		cout.setVisible(true);
		
		// 輸入階梯數
		System.out.print("請輸入階梯最大數量:");
		Scanner s = new Scanner(System.in);
		final int total = s.nextInt();
		System.out.println("注:輸入的爬接替數最大為階梯數-1");
		// 輸入爬樓梯數
		System.out.print("請輸入最大的爬階梯數:");
		Scanner s1 = new Scanner(System.in);
		final int max = s1.nextInt();

		// 判斷爬階梯數是否小於階梯數
		if (total <= max) {
			System.out.println("輸入的爬階梯數過大!");
			return;
		}

		// 輸出爬樓梯情況
		StringBuffer str = new StringBuffer("---->\t");
		System.out.println(total + "階樓梯的爬法總共為:\t"
				+ getMethodCount(total, max, str));
	}

	/*
	 * 爬樓梯情況統計
	 */
	public static int getMethodCount(int total, int max, StringBuffer str) {
		if (0 == total) {
			// 階梯數為0
			System.out.println(str);
			return 1;
		} else if (1 == total) {
			// 階梯數為1,爬樓梯方法就一種,為1,f(1)=1
			System.out.println(str.append("1"));
			return 1;
		} else {	
			// 用於統計爬樓梯的方法總數
			int result = 0;
			for (int i = 1; i <= total; i++) {
				// 存入輸出情況的標題頭
				StringBuffer strBuffD = new StringBuffer(str);


				if (i <= max) {
					result += getMethodCount(total - i, max,
							strBuffD.append(i + "\t"));
				}
			}
			return result;
		}
	}
	
}