题目描述
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
我第一想法是做个树出来,但是算法复杂度太大,说通不过
package easy.dynamicplanning;
import org.junit.Test;
/**
* You are climbing a stair case. It takes n steps to reach to the top.
*
* Each time you can either climb 1 or 2 steps. In how many distinct ways can
* you climb to the top?
*
*
*/
public class ClimbStairs {
class Node{
int val;
Node left;
Node right;
public Node(int val) {
this.val = val;
}
}
int count = 0;
Node root = new Node(0);
public int climbStairs(int n) {
if(n==0)return 0;
if(n==1)return 1;
getTree(root, n, 0);
return count;
}
/**
*
* @param root 当前节点
* @param n
* @param path 当前节点到根节点的路径长度
*/
public void getTree(Node root,int n,int path) {
root = new Node(path);
if(path==n) {
count++;
return;
}
if(path>n) {
return;
}
getTree(root.left, n, path+1);
getTree(root.right, n, path+2);
}
@Test
public void test() {
int n = 3;
int c = climbStairs(n);
System.out.println(c);
}
}
如果是路径问题,特别是问有多少种走法的时侯,要考虑到这一步的走法是不是和前面步数相关,特别是看是不是斐波那契数列
这道题就是斐波那契数列,当问到走法的时候,都是从前一步如何走的总和。
//本质为斐波拉契数列
//1.假设当有n个台阶时假设有f(n)种走法。
//2.青蛙最后一步要么跨1个台阶要么跨2个台阶。
//3.当最后一步跨1个台阶时即之前有n-1个台阶,根据1的假设即n-1个台阶有f(n-1)种走法。
//4. 当最后一步跨2个台阶时即之前有n-2个台阶,根据1的假设即n-2个台阶有f(n-2 )种走法。
//5.显然n个台阶的走法等于前两种情况的走法之和即f(n)=f(n-1)+f(n-2)。
public class Solution {
public int climbStairs(int n) {
int[] dep = new int[n+1];
dep[0] = 1;
dep[1] = 1;
for (int i = 2; i <=n; i++) {
dep[i] = dep[i-1]+dep[i-2];
}
return dep[n];
}
}