Min Cost Climbing Stairs:
I solved this question on leetcode, this problem is based on recursion and dynamic programming. For solving this question we need to go recursion from top to bottom in easy word from last index to start index.
Solution:
func min(a, b int) int {
if a > b {
return b
}
return a
}
func minCostHelper(cost []int, indx int, hashMap map[int]int) int {
//fmt.Println(cost)
if len(cost) == 0 {
return 0
}
if indx == 1 || indx == 0 {
return cost[indx]
}
if val, ok := hashMap[indx]; ok {
return val
}
hashMap[indx] = cost[indx] +
min(minCostHelper(cost, indx-1, hashMap),
minCostHelper(cost, indx-2, hashMap))
return hashMap[indx]
}
func minCostClimbingStairs(cost []int) int {
hashMap := make(map[int]int, 0)
return min(minCostHelper(cost, len(cost)-1, hashMap),
minCostHelper(cost, len(cost)-2, hashMap))
}
0 Comments