作者sustainer123 (caster )
看板Marginalman
標題Re: [閒聊] 每日LeetCode
時間Thu Jan 18 18:48:59 2024
※ 引述《yam276 (史萊哲林的優等生)》之銘言:
: ※ 引述《JerryChungYC (JerryChung)》之銘言:
: : https://leetcode.com/problems/climbing-stairs
: : 70. Climbing Stairs
: : 爬樓梯,要花 n 步
: : 每次只能走 1 步或 2 步,問有幾種走法?
: : 簡單來說就是費氏數列
: : Python3 code:
: : ------------------------------------------------------
: : class Solution:
: : def climbStairs(self, n: int) -> int:
: : a, b = 1, 2
: : for i in range(n-1):
: : a, b = b, a + b
: : return a
: : ------------------------------------------------------
: 以前菜逼C++寫的Code很繁瑣 還用了一個超大Array
: 換成比較簡潔的Rust Style
: Code:
: impl Solution {
: pub fn climb_stairs(n: i32) -> i32 {
: let (mut a, mut b) = (1, 2);
: for _ in 3..=n {
: let next = a + b;
: a = b;
: b = next;
: }
: if n == 1 {a} else {b}
: }
: }
Python3 code:
class Solution:
def climbStairs(self, n: int) -> int:
ans = [0] * (n+2)
ans[1] = 1
ans[2] = 2
for i in range(3,n+1):
ans[i] =(ans[i-1]+ans[i-2])
return ans[n]
EZ
不過分數好醜
等等不設list再跑一次
補字補字
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.137.209.191 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1705574943.A.21C.html
※ 編輯: sustainer123 (223.137.209.191 臺灣), 01/18/2024 18:49:41
→ JIWP: 大師 01/18 18:49
→ OAOb: 你怎麼跑去學py了 01/18 18:50
→ sustainer123: 用C刷題太麻煩 01/18 18:54
推 SecondRun: 大師 幾天就精通py了 01/18 19:03
→ yam276: 你要學Rust 01/19 12:04