Skip to content

Commit

Permalink
add ago day 39 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
ChiShouWu committed Aug 26, 2021
1 parent a23437b commit 81cee08
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
22 changes: 22 additions & 0 deletions 2021-08/2021-08-26 (day39)/AGO/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# 70. Climbing Stairs

`Easy`

## Description

<p>You are climbing a staircase. It takes <code>n</code> steps to reach the top.</p>

<p>Each time you can either climb <code>1</code> or <code>2</code> steps. In how many distinct ways can you climb to the top?</p>

## 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)
27 changes: 27 additions & 0 deletions 2021-08/2021-08-26 (day39)/AGO/solution.ts
Original file line number Diff line number Diff line change
@@ -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;
};

0 comments on commit 81cee08

Please sign in to comment.