题目如下
写出 f(n)=f(n-1)+f(n-m) 的非递归写法,其中n<m时 f(n)= 1 ,题目来源好像是来自英伟达。
为了更好的理解,建议先看懂《剑指offer》74页的菲波那切数列斐波那契的非递归写法。
思想如出一辙,就是保证每次都保存前m个计算结果,这样计算的时候直接取出n-m所在空间的数据f(n-m)然后相加就好了,效率会比递归高很多。
关键点来了:每次计算后需要更新,因为下一次n就变成了n+1了 ,那么我需要的取出的数就变成了n+1-m了,也就是说我们只要全体移动一位就行了,将上一次运算的结果保存到下一次计算中。当然那个被丢弃的数据我们再也不需要用到它了,![偷笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)
![偷笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)
,这样保证在下一次n+1的时候始终保持正
![偷笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)
![偷笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)
![偷笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/titter.gif)