摘要:無需動規(guī),無需額外空間,等同于菲波那切數(shù)列。當然嚕,也可以動規(guī),記住就好。
Problem
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?
ExampleGiven an example n=3 , 1+1+1=2+1=1+2=3
return 3
Note無需動規(guī),無需額外空間,等同于菲波那切數(shù)列。
當然嚕,也可以動規(guī),記住dp[0] = 1就好。
public class Solution { public int climbStairs(int n) { if (n < 2) return 1; int one = 1, two = 1, total = 0; for (int i = 2; i <= n; i++) { res = one + two; two = one; one = res; } return res; } }DP
public class Solution { public int climbStairs(int n) { int[] dp = new int[n+1]; dp[0] = 1; dp[1] = 1; for (int i = 2; i <= n; i++) dp[i] = dp[i-1] + dp[i-2]; return dp[n]; } }
文章版權歸作者所有,未經(jīng)允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/65789.html
Problem A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. Ex...
摘要:遞歸法復雜度時間空間思路這題幾乎就是求解斐波那契數(shù)列。最簡單的方法就是遞歸。但重復計算時間復雜度高。代碼遞推法復雜度時間空間思路實際上我們求的時候只需要和的值,所以可以減少一些空間啊。 Climbing Stairs You are climbing a stair case. It takes n steps to reach to the top. Each time you c...
摘要:實質就是把之前出現(xiàn)過的中間結果記錄,下次再出現(xiàn)相同情況的時候,通過可以只用的時間復雜度得到。表示到達第層樓梯的不同走法。那么題目中每次可以選擇走一步,或者兩步,。從迭代公式可以知道,有兩個,和。 70. Climbing Stairs You are climbing a staircase. It takes n steps to reach to the top.Each tim...
746. Min Cost Climbing Stairs On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find mini...
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? Note: Given n will be a positive i...
閱讀 1191·2023-04-26 02:38
閱讀 1486·2021-11-22 09:34
閱讀 1193·2021-09-26 10:19
閱讀 3182·2019-08-29 17:15
閱讀 3534·2019-08-29 12:27
閱讀 1723·2019-08-26 13:51
閱讀 1870·2019-08-26 13:47
閱讀 1021·2019-08-26 12:20