记忆化搜索
记忆化搜索是用来处理递归中的重复计算问题,不要小看这个问题,因为这个问题可能把你的程序的性能拉下谷底,复杂度可以达到$$O(2^N)$$。
简单的说:就是将递归中产生的结果值进行储存,在重复使用时可以直接拿来使用。
是用空间换时间的方法,但很值得一换
例如:
题1:
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
实现1:
int f1(int x) {timer1++;return (x ==0||x==1) ? 1 : f1(x-1)+f1(x-2);}
实现2:
int dp[50];
int f(int x) {
shen++;
if(x == 0 || x == 1 ){ dp[0] = 1;dp[1] = 1; return 1;}
if(dp[x] != -1) return dp[x];
return dp[x]= f(x - 2)+f( x - 1);
}
结果:

师傅的代码:

精简优美
师傅博客:http://ofpsxx.com
浙公网安备 33010602011771号