window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/","ext":".png","svgUrl":"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/svg\/","svgExt":".svg","source":{"concatemoji":"https:\/\/zyrastory.com\/wp-includes\/js\/wp-emoji-release.min.js?ver=6.1.1"}};
/*! This file is auto-generated */
!function(e,a,t){var n,r,o,i=a.createElement("canvas"),p=i.getContext&&i.getContext("2d");function s(e,t){var a=String.fromCharCode,e=(p.clearRect(0,0,i.width,i.height),p.fillText(a.apply(this,e),0,0),i.toDataURL());return p.clearRect(0,0,i.width,i.height),p.fillText(a.apply(this,t),0,0),e===i.toDataURL()}function c(e){var t=a.createElement("script");t.src=e,t.defer=t.type="text/javascript",a.getElementsByTagName("head")[0].appendChild(t)}for(o=Array("flag","emoji"),t.supports={everything:!0,everythingExceptFlag:!0},r=0;r<o.length;r++)t.supports[o[r]]=function(e){if(p&&p.fillText)switch(p.textBaseline="top",p.font="600 32px Arial",e){case"flag":return s([127987,65039,8205,9895,65039],[127987,65039,8203,9895,65039])?!1:!s([55356,56826,55356,56819],[55356,56826,8203,55356,56819])&&!s([55356,57332,56128,56423,56128,56418,56128,56421,56128,56430,56128,56423,56128,56447],[55356,57332,8203,56128,56423,8203,56128,56418,8203,56128,56421,8203,56128,56430,8203,56128,56423,8203,56128,56447]);case"emoji":return!s([129777,127995,8205,129778,127999],[129777,127995,8203,129778,127999])}return!1}(o[r]),t.supports.everything=t.supports.everything&&t.supports[o[r]],"flag"!==o[r]&&(t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&t.supports[o[r]]);t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&!t.supports.flag,t.DOMReady=!1,t.readyCallback=function(){t.DOMReady=!0},t.supports.everything||(n=function(){t.readyCallback()},a.addEventListener?(a.addEventListener("DOMContentLoaded",n,!1),e.addEventListener("load",n,!1)):(e.attachEvent("onload",n),a.attachEvent("onreadystatechange",function(){"complete"===a.readyState&&t.readyCallback()})),(e=t.source||{}).concatemoji?c(e.concatemoji):e.wpemoji&&e.twemoji&&(c(e.twemoji),c(e.wpemoji)))}(window,document,window._wpemojiSettings);
https://zyrastory.com/wp-includes/js/jquery/jquery.min.js
https://zyrastory.com/wp-includes/js/jquery/jquery-migrate.min.js
jQuery(document).ready(function(){document.querySelectorAll(".ez-toc-section").forEach(t=>{t.setAttribute("ez-toc-data-id","#"+decodeURI(t.getAttribute("id")))}),jQuery("a.ez-toc-link").click(function(){let t=jQuery(this).attr("href"),e=jQuery("#wpadminbar"),i=0;30>30&&(i=30),e.length&&(i+=e.height()),jQuery('[ez-toc-data-id="'+decodeURI(t)+'"]').length>0&&(i=jQuery('[ez-toc-data-id="'+decodeURI(t)+'"]').offset().top-i),jQuery("html, body").animate({scrollTop:i},500)})});
(function(c,l,a,r,i,t,y){ c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)}; t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i+"?ref=bwt"; y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y); })(window, document, "clarity", "script", "btkbh92jgl");
Skip to content
LeetCode題目翻譯英文原文如下
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
中文翻譯
你在爬樓梯,總共有n階才能到達最高處
每次你只能爬1或2階,試問總共有幾種方法可以爬到最高處?
題目約束 n為介於1到45之間的數字,故不需要考慮步數不在其中的情況
現在來看看範例
官方的範例共兩個,n分別為 2 跟 3
n為2時,共有兩種走法,分別為
n為3時,共有兩種走法,分別為
解題思路首先假設答題函式為Fn(n)
現在先來統整一下已知的事
現在我們來假設一下 n 為 3 時的情況
首先我們能選擇的僅有兩種可能,一步或兩步 對吧
故出現以下兩種分支
大家有沒有發現剩下的兩種步數我們都知道總共有幾種方法了
分別為Fn(2)= 2 跟Fn(1) = 1
故上面的兩種分支該改為以下
先走一步,剩下兩步 Fn(2)= 2 先走兩步,剩下一步 Fn(1) = 1 故得到結論 : Fn(3) = Fn(2)+Fn(1) = 2+1 = 3
下一個我們換來假設 n 為 4 時的情況
一樣是只能先選擇走一步或兩步
先走一步,剩下三步 Fn(3) = 3 (剛剛得到熱騰騰的結論) 先走兩步,剩下兩步 Fn(2) = 2 故得到結論 : Fn(4) = Fn(3)+Fn(2) = 3+2 = 5
相信這時候,有聰明的小夥伴就看出來了,好像有個規律對不對!
這時候我們來進行最後一次假設,假設 所需步數為 n 時的情況
先走一步,剩下 n-1 步 Fn(n-1) 先走兩步,剩下 n-2 步 Fn(n-2) 故得到結論 : Fn(n) = Fn(n-1)+Fn(n-2)
費波那契數 Fibonacci 這一題其實就是一個經典的費波那契數
修等幾勒,你說你沒聽過
這張圖應該就見過了吧
大家可以觀察上面這張圖會發現每個數字都是由前面兩個數字相加組成
2 = 1+1
3 = 2+1
5 = 3+2
8 = 5+3
等等,這不就跟我們的題目有點像嗎!
更詳細的資料請參閱維基百科
解題思路(程式) 現在讓我們用程式來實現剛剛的想法 (文章會以C#作為範例說明,其他語言不一定會特別解釋)
C# 解決方案 方案1 – 使用變數來儲存
public class Solution {
public int ClimbStairs(int n) {
int first = 1; //樓梯為1階,僅有1步這種方法
int second = 2; //樓梯為2階,有 1+1 、 一次2步 兩種走法
int tmp = 0;
if(n<=2) //若n小於等於2則直接回傳結果(剛好1階2階直接對應至幾種走法)
{
return n;
}
else
{
for(int i =3; i<=n;i++) //每次進入時,會將前兩次之步數加總存於second
{
tmp = second;
second+=first; //設second為目前所需步數
first = tmp; //設first為上一次所需步數
}
}
return second;
}
}
方案2 – 使用陣列來儲存
public class Solution {
public int ClimbStairs(int n) {
if(n<2){
return n;
}
int[] ans = new int[n];
ans[0] = 1;
ans[1] = 2;
for(int i=2;i<n;i++) {
ans[i]=ans[i-1]+ans[i-2];
}
return ans[n-1];
}
}
跟第一個寫法其實差不多,只是使用陣列取代了變數
Java解 決方案方案1
class Solution {
public int climbStairs(int n) {
if(n<2){
return n;
}
int first = 1;
int second = 2;
int tmp = 0;
for(int i =3; i<=n;i++) {
tmp = second;
second+=first;
first = tmp;
}
return second;
}
}
方案2
class Solution {
public int climbStairs(int n) {
if(n<2){
return n;
}
int[] ans = new int[n];
ans[0] = 1;
ans[1] = 2;
for(int i=2;i<n;i++) {
ans[i]=ans[i-1]+ans[i-2];
}
return ans[n-1];
}
}
Python3 解決方案方案1 – 用list來作儲存
class Solution:
def climbStairs(self, n: int) -> int:
if(n<2):
return n;
ans = [1,2];
for i in range(2, n):
ans.append(ans[i-1]+ans[i-2]);
return ans[n-1];
JavaScript 解決方案方案1
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
let arr = [1,2];
for (var i = 2; i<n; i++) {
arr[i]=arr[i-1]+arr[i-2];
}
return arr[n-1];
};
結論 這題題目本身其實並不複雜,難的在於如何得出規律。
筆者當初也是抱著頭思考著,突然靈機一動才想到解答!
題目連結 : Climbing Stairs – LeetCode
🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸
🧡可以的話,幫我的FaceBook 粉絲專頁按個讚,我會很感謝的
✅如有任何疑問,歡迎透過留言或messenger讓我知道 !
*補充 : 與本題相關,算是變形的另一道題目 LeetCode #118 Pascal’s Triangle 解題思路及翻譯 – zyrastory程式美食研究中心
"眾裡尋他千百度,驀然回首,那人卻在,燈火闌珊處"
最新文章
LeetCode 教學 LeetCode C#解答 , LeetCode JavaScript 解答 , LeetCode Java解答 , LeetCode Python 解答 , LeetCode 教學 Search More LeetCode Problems
Continue Reading
jQuery(".jq-goTop").click(function (e) {
e.preventDefault();
let hi = jQuery(window).scrollTop();
hi = hi/2.5;
jQuery("html,body").animate(
{
scrollTop: 0,
},
hi
);
window.girl = 0;
var clock = setInterval(testFunc, 150);
setTimeout(function()
{
clearInterval(clock);
jQuery("#walking_girl0").hide();
jQuery("#walking_girl1").hide();
jQuery("#walking_girl2").hide();
},hi);
});function testFunc()
{
//console.log(window.girl);
switch(window.girl)
{
case 0:
jQuery("#walking_girl0").show();
jQuery("#walking_girl1").hide();
jQuery("#walking_girl2").hide();
break;
case 1:
jQuery("#walking_girl0").hide();
jQuery("#walking_girl1").show();
jQuery("#walking_girl2").hide();
break;
case 2:
jQuery("#walking_girl0").hide();
jQuery("#walking_girl1").hide();
jQuery("#walking_girl2").show();
break;
}
window.girl = window.girl == 2 ? 0 : window.girl+1;
}
function closePop(){document.getElementById("headlineatas").style.display = 'none';}
function openPop()
{
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent))
{
return false;
}
var r = Math.random();
if(r>0.7 || r<0.3)
{
document.getElementById("headlineatas").style.display = '';
}
}
function getFocus() {
//document.getElementById("wp-block-search__input-1").focus();
document.querySelector("#secondary > form > label > input").focus();
}
(adsbygoogle = window.adsbygoogle || []).push({});
(adsbygoogle = window.adsbygoogle || []).push({});
(adsbygoogle = window.adsbygoogle || []).push({});
(adsbygoogle = window.adsbygoogle || []).push({});
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
js = d.createElement(s); js.id = id;
js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js#xfbml=1&version=v6.0&autoLogAppEvents=1'
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function returnDefault(item)
{
item.innerText = "Copy"
item.style.color = "white"
item.style.backgroundColor = "CornflowerBlue";
}
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) == false) //20221128 手機用戶移除copy功能
{
jQuery('code').each(function () {
var btn = document.createElement("button");
btn.innerHTML = "Copy";
btn.onmousedown = "event.preventDefault();";
btn.setAttribute('class', 'btnC');
btn.onclick = function(){
var k = this.nextSibling;
var textArea = document.createElement("textarea");
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';// Avoid flash of the white box if rendered for any reason.
textArea.style.background = 'transparent';textArea.value = k.textContent;document.body.appendChild(textArea);
textArea.focus();
textArea.select();var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';if(successful)
{
this.focus();
this.style.backgroundColor = "green";
this.innerText = "✔Copied"
openPop();
setTimeout(( ()=>returnDefault(this)),1850)
}document.body.removeChild(textArea);
};var parent = this.parentNode;
parent.insertBefore(btn, this);
});
}
https://zyrastory.com/wp-content/themes/responsiveblogily/js/navigation.js
https://zyrastory.com/wp-content/themes/responsiveblogily/js/skip-link-focus-fix.js
https://zyrastory.com/wp-content/themes/responsiveblogily/js/script.js
https://zyrastory.com/wp-content/themes/responsiveblogily/js/jquery.flexslider.js
https://zyrastory.com/wp-content/themes/responsiveblogily/js/accessibility.js
https://zyrastory.com/wp-includes/js/comment-reply.min.js
https://zyrastory.com/wp-content/plugins/highlighting-code-block/assets/js/prism.js
https://zyrastory.com/wp-content/plugins/highlighting-code-block/build/js/hcb_script.js
https://zyrastory.com/wp-content/plugins/easy-table-of-contents/vendor/js-cookie/js.cookie.min.js
https://zyrastory.com/wp-content/plugins/easy-table-of-contents/vendor/sticky-kit/jquery.sticky-kit.min.js
var ezTOC = {"smooth_scroll":"1","visibility_hide_by_default":"","width":"auto","scroll_offset":"30"};
https://zyrastory.com/wp-content/plugins/easy-table-of-contents/assets/js/front.min.js
(function() {
var expirationDate = new Date();
expirationDate.setTime( expirationDate.getTime() + 31536000 * 1000 );
document.cookie = "pll_language=zh; expires=" + expirationDate.toUTCString() + "; path=/; secure; SameSite=Lax";
}());
/(trident|msie)/i.test(navigator.userAgent)&&document.getElementById&&window.addEventListener&&window.addEventListener("hashchange",function(){var t,e=location.hash.substring(1);/^[A-z0-9_-]+$/.test(e)&&(t=document.getElementById(e))&&(/^(?:a|select|input|button|textarea)$/i.test(t.tagName)||(t.tabIndex=-1),t.focus())},!1);
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};