我遇到的问题是
一个孩子正在爬楼梯,有n个台阶, 并且可以一次跳1步,2步或3步。 实施一种方法来计算孩子爬楼梯的可能方式。
http://play.golang.org/p/bpjIkMm9jH
package main
import "fmt"
func CountWaysDP(n int, mm map[int]int) int {
if n < 0 {
return 0
} else if n == 0 {
return 1
} else if mm[n] > -1 {
return mm[n]
} else {
mm[n] = CountWaysDP(n-1, mm) +
CountWaysDP(n-2, mm) +
CountWaysDP(n-3, mm)
return mm[n]
}
}
func main() {
mm := make(map[int]int)
fmt.Println(CountWaysDP(10, mm), mm)
}
这只给了我0 map []。事实证明,动态递归在以下行结束:
else if mm[n] > -1
那么我如何使用动态编程来解决这个问题呢?这与破解编码面试完全相同......
答案 0 :(得分:2)
您需要与0进行比较:
else if mm[n] > 0
获取非现有密钥的值时,map返回0。
你也可以使用数组/切片代替map,因为你知道地图键总是从1到N
你也可以在没有递归的情况下解决这个问题:
package main
import "fmt"
func main() {
n := 10
mm := make([]int, n+1)
mm[0] = 1
for i := 1; i <= n; i++ {
for k := 1; k <= 3; k++ {
if i-k >= 0 {
mm[i] += mm[i-k]
}
}
}
fmt.Println(mm)
fmt.Println(mm[n])
}
答案 1 :(得分:0)
分而治之的Python解决方案:
def staircase_count(nSteps):
if nSteps < 0:
return 0
if nSteps == 0:
return 1
total = 0
for step in [1, 2, 3]:
total += staircase_count(nSteps - step)
return total
assert staircase_count(1) == 1
assert staircase_count(2) == 2
assert staircase_count(3) == 4
assert staircase_count(4) == 7
答案 2 :(得分:-1)
JavaScript解决方案:(迭代)
function countPossibleWaysIterative(n) {
if (n < 0){
return -1; // check for negative, also might want to check if n is an integer
} if (n === 0) {
return 0; // for case with 0 stairs
} else if (n === 1) {
return 1; // for case with 1 stairs
} else if (n === 2) {
return 2; // for case with 2 stairs
} else {
var prev_prev = 1;
var prev = 2;
var res = 4; // for case with 3 stairs
while (n > 3) { // all other cases
var tmp = prev_prev + prev + res;
prev_prev = prev;
prev = res;
res = tmp;
n--;
}
}
return res;
}