39级台阶(竞赛题,Go语言实现)

问题重现:

小明刚刚看完电影《第39级台阶》,离开电影院的时候,他数了数礼堂前的台阶数,恰好是39级!

站在台阶前,他突然又想着一个问题:

如果我每一步只能迈上1个或2个台阶。先迈左脚,然后左右交替,最后一步是迈右脚,也就是说一共要走偶数步。那么,上完39级台阶,有多少种不同的上法呢?

请你利用计算机的优势,帮助小明寻找答案。

 

递归解决方案(Go语言实现)

package main

import (
	"fmt"
)

/*递归核心  作者:天之
*@i表示爬楼梯次数
*@now表示当前所在楼层
*@top表示楼梯总层数
*@*count计满足条件的数
 */
func f(i, now, top int, count *int) {
	if now == top {
		//最后必须迈右脚,0迈左脚,1迈右脚
		//结束时i多加了1,故判断时和0比较
		if (i&1) == 0 {
			(*count)++
		}

	} else if now < top {
		f(i+1, now+1, top, count)
		f(i+1, now+2, top, count)
	}
}
func main() {
	var count int = 0
	var top int = 39
	//从键盘获取输入总级数
	fmt.Scanf("%d", &top)
	f(0, 0, top, &count)
	fmt.Println(count)
	//让屏幕暂留
	fmt.Scanf("%c", &top)
	fmt.Scanf("%c", &top)
}

 

点赞