zoukankan      html  css  js  c++  java
  • 动态规划--上楼梯

    题目:假设你需要进入一个房间,但是房间在楼上,你需要走完n阶台阶,才能到楼上,如果你一次性可以走1、2或3个台阶,可以计算出你一共有多少种方案去走完所有的台阶进入房间呢?

    解题思路:定义一个状态函数f(n)用来表示如果要走n阶台阶一共可以有方案数量,则f(n)=f(n-1)+f(n-2)+f(n-3)。当n=1时只有一中方案,当n=2时有两种方案(1,1;2),当n=3时有4种方案(1,1,1;1,2;2,1;3),依次类推。

    具体算法(Java版)

     1 /**
     2  * 计算n个台阶一共有多少种走法
     3  */
     4 public class Step {
     5 
     6     public static int walk(int n, int[] stepWays) {
     7         if (n <= 0)
     8             return 0;
     9         int count = 0;
    10         for (int i = 0; i < stepWays.length; i++) {
    11             if (n == stepWays[i]) {
    12                 count += 1;
    13             } else {
    14                 count += walk(n - stepWays[i], stepWays);
    15             }
    16         }
    17         return count;
    18     }
    19 
    20     public static void main(String[] args) {
    21         int[] stepWays = new int[] { 3, 1, 2};
    22         int n = 10;
    23         System.out.println(walk(n, stepWays));
    24     }
    25 
    26 }

    如果有什么问题,可以一起交流! 

  • 相关阅读:
    如何将网站升级为HTTPS协议?
    hashmap:cr:csdn
    HashMap的底层原理 cr:csdn:zhangshixi
    servlet
    泛型,反射
    线程

    集合
    java基础题
    我的博客网址
  • 原文地址:https://www.cnblogs.com/pinxiong/p/5870337.html
Copyright © 2011-2022 走看看