[C++ Solutions for Dynamic Programming] Climbing Stairs
Climbing Stairs
1. Code
- Each time you can either climb 1 or 2 steps
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int climbStairs(int n) {
if (n == 1) return 1;
if (n == 2) return 2;
int prev1 = 2;
int prev2 = 1;
int current = 0;
for (int i = 3;i < n+1; i++) {
current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
return prev1;
}
};
Reviews
1. Fibonacci
The problem is similar to calculating the Fibonacci sequence becuase it has a structure where the current state is calcuated
based on the previous states
The reason why
\[ways(n) = ways(n-1) + ways(n+2)\]n-1 step, adding 1 step will take you to the n-th step
n-2 step, adding 2 steps will take you to the n-th step
So, n-th step is the sum of all the ways to reach
n-1 step + n-2 step
Github Blog (Customize the tag page)
1. Uppercase in Tag Slugs (generate_tags.rb)
gsub
to convert spaces in tags to hyphens (-), while preserving case.Tags like
API
will now correctly generate pages with their original case (i.e., API, not api)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
module Jekyll
class TagPageGenerator < Generator
safe true
def generate(site)
site.tags.each do |tag, posts|
# Use slugify with 'raw' mode to preserve case
slug = tag.gsub(' ', '-').gsub(/[^\w-]/, '') # Keep the original case in the slug
site.pages << TagPage.new(site, site.source, File.join('tags', slug), tag)
end
end
end
class TagPage < Page
def initialize(site, base, dir, tag)
@site = site
@base = base
@dir = dir
@name = 'index.html'
self.process(@name)
self.read_yaml(File.join(base, '_layouts'), 'tag.html')
self.data['tag'] = tag
self.data['title'] = "Posts tagged as \"#{tag}\""
end
end
end
2. Update Tag URL (post.html)
- Jekyll
slugify
method converts tags to lowercase. So, add themode : 'raw'
option, which preserves the original case
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!-- tags -->
<div class="post-tags">
<i class="fa fa-tags fa-fw me-1"></i>
<a
href="/tags/c%2B%2B/"
class="post-tag no-text-decoration"
>c++<!-- Display the tag as-is, preserving case -->
</a>
<a
href="/tags/python/"
class="post-tag no-text-decoration"
>python<!-- Display the tag as-is, preserving case -->
</a>
<a
href="/tags/algorithm/"
class="post-tag no-text-decoration"
>algorithm<!-- Display the tag as-is, preserving case -->
</a>
<a
href="/tags/jekyll/"
class="post-tag no-text-decoration"
>jekyll<!-- Display the tag as-is, preserving case -->
</a>
</div>
3. Modifying to Exclude Tag Pages (page.html)
page.html
layout, which includes adynamic-title
, was conflicting with the tag pages (causing duplicate titles)To fix this, I added a condition to exclude tag pages from displaying the
dynamic-title
This post is licensed under CC BY 4.0 by the author.