From 81cee08f4bfcb87a0fea3b3b8ef4cc7d39c3369c Mon Sep 17 00:00:00 2001 From: chishouwu Date: Thu, 26 Aug 2021 21:12:22 +0800 Subject: [PATCH] add ago day 39 solution --- 2021-08/2021-08-26 (day39)/AGO/README.md | 22 ++++++++++++++++++ 2021-08/2021-08-26 (day39)/AGO/solution.ts | 27 ++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 2021-08/2021-08-26 (day39)/AGO/README.md create mode 100644 2021-08/2021-08-26 (day39)/AGO/solution.ts diff --git a/2021-08/2021-08-26 (day39)/AGO/README.md b/2021-08/2021-08-26 (day39)/AGO/README.md new file mode 100644 index 00000000..55fd17af --- /dev/null +++ b/2021-08/2021-08-26 (day39)/AGO/README.md @@ -0,0 +1,22 @@ +# 70. Climbing Stairs + +`Easy` + +## Description + +

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?

+ +## My thought + +steps to 5 equals `step 3 combinations + 2 steps `or `step 3 combiations + 1 step`. + +So we can create a DP `f(n) = f(n-1) + f(n-2)` +There is two way + +1. Recursive from the end. +2. Store steps spend into an array and loop from step 3 to end, plus previous steps and more previous steps. + `To save more menmory, we can just store 2 steps previous without whole route` + +## O(N) diff --git a/2021-08/2021-08-26 (day39)/AGO/solution.ts b/2021-08/2021-08-26 (day39)/AGO/solution.ts new file mode 100644 index 00000000..446ac4e7 --- /dev/null +++ b/2021-08/2021-08-26 (day39)/AGO/solution.ts @@ -0,0 +1,27 @@ +// solution1 +function climbStairs(n: number): number { + let stairs:number[] = new Array(); + stairs[1] = 1; + stairs[2] = 2; + + for(let i = 3; i<=n;i++){ + stairs[i] = stairs[i-1] + stairs[i-2]; + } + return stairs[n]; +}; +// solution2 +function climbStairs(n: number): number { + if (n==1) return 1; + if (n==2) return 2; + + let oneStepBefore = 2; + let twoStepBefore = 1; + let ans = 2; + for(let i = 3; i<=n;i++){ + ans = oneStepBefore + twoStepBefore; + let temp = oneStepBefore; + oneStepBefore = ans; + twoStepBefore = temp; + } + return ans; +}; \ No newline at end of file