p22 爬楼梯方法数 (leetcode 70)

一:解题思路

这道题目是一道简单的动态规划题目。有2种方法,第一种为递归法。第二种为迭代法。

二:完整代码示例 (C++版和Java版)

第一种方法:C++

 class Solution 
 {
 public:
     int climbStairs(int n) 
     {
         if (1 == n) return 1;
         if (2 == n) return 2;

         return climbStairs(n-1) + climbStairs(n-2);
     }
 };

第一种方法Java:

class Solution 
{
    public int climbStairs(int n) 
    {
           if(1==n) return 1;
           if(2==n) return 2;
           
           return climbStairs(n-1)+climbStairs(n-2);
    }
}

迭代法:C++

 class Solution 
 {
 public:
     int climbStairs(int n) 
     {
         int first = 1;
         int second= 1;

         for (int i = 1; i < n; i++)
         {
             int third = first + second;

             first = second;
             second = third;
         }

         return second;
     }
 };

迭代法:Java

class Solution
{
    public int climbStairs(int n)
    {
           int first=1;
           int second=1;
           
           for(int i=1;i<n;i++)
           {
               int third=first+second;
               
               first=second;
               second=third;
           }
           
           return second;
    }
}

猜你喜欢

转载自www.cnblogs.com/repinkply/p/12470422.html
今日推荐