golang 爬楼梯算法(递归&非递归)
发布时间:2021-12-25 编辑:jiaochengji.com
教程集为您提供golang 爬楼梯算法(递归&非递归)等资源,欢迎您收藏本站,我们将为您提供最新的golang 爬楼梯算法(递归&非递归)资源
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"/></svg><h2>题目:</h2>
<h2>递归方法</h2>
递归实现的可读性高,实现简单。
<pre><code>func ClimbStairs(n int) int { var count int = 0 Climb(0, n, &count) return count } // current 当前爬的楼梯数 // n 目标楼梯数 // count 计数 func Climb( current, n int, count *int) { if current == n { *count return } if current 1 <= n { Climb(current 1, n, count) } if current 2 <= n { Climb(current 2, n, count) } } </code></pre> <h2>非递归方法</h2>先定义一个栈
<pre><code>type Stack struct { slc []int } func (s *Stack) Push(a int) { s.slc = append(s.slc, a) } func (s *Stack) Pop() int { a := s.slc[len(s.slc)-1] s.slc = s.slc[:len(s.slc)-1] return a } func (s *Stack) Len() int { return len(s.slc) } </code></pre>使用栈来替代递归方案
<pre><code>// 非递归方法 func ClimbStairs(n int) int { count := 0 stack := &Stack{slc: []int{0}} // 初始化 for stack.Len() > 0 { current := stack.Pop() if current == n { count continue } if current 1 <= n { stack.Push(current 1) } if current 2 <= n { stack.Push(current 2) } } return count } </code></pre> <h2>基准测试</h2>
非递归方式要快一点。
您可能感兴趣的文章:
golang 爬楼梯算法(递归&非递归)
后端面试(Golang)可能会碰上的附加智力题
阶梯问题的递归解法
Golang算法:二叉树前序,中序,后序非递归遍历算法
php递归调用的小例子
php递归创建目录小例子
一文了解Python中的递归
php递归示例 php递归函数代码
go-zookeeper递归获取接口
【golang】算法 -- 快速排序
[关闭]