Skip to content

Instantly share code, notes, and snippets.

@hkaya15
Created June 25, 2022 23:38
Show Gist options
  • Save hkaya15/47f7c0fc16211dbb56a4ee7a6590774d to your computer and use it in GitHub Desktop.
Save hkaya15/47f7c0fc16211dbb56a4ee7a6590774d to your computer and use it in GitHub Desktop.
// Tabulation
func tabulation_getminstairs(n int) int {
table := make([]int, n+1)
for i := 2; i <= n; i++ {
if (i%2 == 0) && i%3 != 0 {
table[i] = 1 + int(math.Min(float64(table[i-1]), float64(table[i/2])))
} else if (i%3 == 0) && i%2 != 0 {
table[i] = 1 + int(math.Min(float64(table[i-1]), float64(table[i/3])))
} else if (i%2 == 0) && (i%3 == 0) {
table[i] = 1 + int(math.Min(float64(table[i-1]), math.Min(float64(table[i/2]), float64(table[i/3]))))
} else {
table[i] = 1 + table[i-1]
}
}
return table[n]
}
// Memoization
func memoization_getminstairs(n int, memo []int) int {
if n == 1 {
return 0
}
if memo[n] != 0 {
return memo[n]
}
result := memoization_getminstairs(n-1, memo)
if n%2 == 0 {
result = int(math.Min(float64(result), float64(memoization_getminstairs(n/2, memo))))
}
if n%3 == 0 {
result = int(math.Min(float64(result), float64(memoization_getminstairs(n/3, memo))))
}
memo[n] = 1 + result
return memo[n]
}
// Recursion
func recursive_getminstairs(n int) int {
if n == 1 {
return 0
}
result := recursive_getminstairs(n - 1)
if n%2 == 0 {
result = int(math.Min(float64(result), float64(recursive_getminstairs(n/2))))
}
if n%3 == 0 {
result = int(math.Min(float64(result), float64(recursive_getminstairs(n/3))))
}
return result + 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment