參考博文:
http://blog.csdn.net/feixiaoxing/article/details/6871148
問題:
有一個人準備開始爬樓梯,假設樓梯有n個,這個人只允許一次爬一個樓梯或者一次爬兩個樓梯,請問有多少種爬法?
思路:每步所在的樓梯第n層,要麼從第n-2層爬過來,要麼從第n-1層爬過來,除此之外別無其他狀態。
所以可以採用遞歸的思想,從上向下依次處理。
運行結果截圖:
完整代碼:
package edu.ynu.test;
import java.util.Enumeration;
import java.util.Stack;
public class jumpLadder {
/*
* @layer 所在樓梯index
* @stack 用於保存每一步的狀態
* @top 步數
*/
public static void jump_ladder(int layer,Stack<Integer> stack,int top)
{
//樓層參數合法
if(layer<=0)
return;
if(layer==1)
{
printStack( stack,1);
}
if(layer==2)
{
printStack( stack,2);
}
_jump_ladder(layer,stack,1,top);
//***防止堆棧累計壓入數據***
while(stack.size()>top)
{
stack.pop();
}
_jump_ladder(layer,stack,2,top);
}
//每一步的相應處理
public static void _jump_ladder(int layer,Stack<Integer> stack,int decrease,int top)
{
top++;//步數加1
stack.push(decrease);//壓棧
layer=layer-decrease;//減去每部的狀態(採用從上向下的方式)
jump_ladder(layer,stack,top);//遞歸
}
/*
* 打印堆棧
*/
public static void printStack(Stack<Integer> stack,int last)
{
System.out.print("# "+last+" ");
if(stack.empty())
System.out.print(" ");
else
{
//顯示枚舉所有stack中的元素
Enumeration<Integer> items=stack.elements();
while(items.hasMoreElements())
System.out.print(items.nextElement()+" ");
}
System.out.println("#");
}
/**
* @author wxx
* 問題:有一個人準備開始爬樓梯,假設樓梯有n個,
* 這個人只允許一次爬一個樓梯或者一次爬兩個樓梯,
* 請問有多少種爬法?
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int Layer=6;//樓層數
Stack<Integer> stack=new Stack<Integer>();//聲明堆棧
System.out.println("該樓層共有 "+Layer+" 級臺階");
System.out.println("\n所有的爬法如下:");
jump_ladder(Layer,stack,0);
}
}