日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode Climbing Stairs

發(fā)布時(shí)間:2025/5/22 编程问答 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode Climbing Stairs 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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 int climbStairs2(int n) {if (n == 0)return 1;if (n < 3)return n;return climbStairs(n - 1) + climbStairs(n - 2);}

?

方法二:用臨時(shí)變量保存前面兩個(gè)數(shù)

public int climbStairs(int n) {if (n <= 0)return n == 0 ? 1 : 0;int result = 0;if (n < 3)return n;int pre = 1;int last = 2;for (int i = 3; i <= n; i++) {result = last + pre;pre = last;last = result;}return result;}

總結(jié):方法一之所以能夠優(yōu)化為方法二是因?yàn)榉椒ㄒ挥?jì)算了f(n-1)和f(n-2)(注意:這里f(n)指的是爬上第n階的方法數(shù)),因此我們用兩個(gè)臨時(shí)變量保存就好了

與這題類(lèi)似的另外一個(gè)題是:

There is a fence with?n?posts, each post can be painted with one of thek?colors.
You have to paint all the posts such that no more than two adjacent fence posts have the same color.
Return the total number of ways you can paint the fence.

該題也是類(lèi)似的原理

public class Solution {/*** @param n non-negative integer, n posts* @param k non-negative integer, k colors* @return an integer, the total number of ways*/public int numWays(int n, int k) {if (n == 0 || k == 0)return 0;if (n < 3) {return n == 1 ? k : k * k;}int pre = k;int last = k * k;int result = 0;for (int i = 3; i <= n; n++) {result = (k - 1) * pre + (k - 1) * last;pre = last;last = result;}return result;} }

?

轉(zhuǎn)載于:https://www.cnblogs.com/googlemeoften/p/5833911.html

總結(jié)

以上是生活随笔為你收集整理的LeetCode Climbing Stairs的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。