publicstaticvoidmain(String[] args){ long start = System.currentTimeMillis(); long i = fib(10000); long end = System.currentTimeMillis() - start; System.out.println("time:"+end + "ms," + i); }
publicstaticvoidmain(String[] args){ long start = System.currentTimeMillis(); int n = 50; res = newlong[n+1]; for(int i = 0; i < n;i++){ //初始化数组 res[i] = -1; } long r = fib(n); long end = System.currentTimeMillis() - start; System.out.println("time:"+end + "ms," + r); }
同样求解 n= 50 ,运行结果:time:0ms,12586269025
求解 n = 1000 ,运行结果:time:0ms,817770325994397771
在经过消除冗余后,时间复杂度O(n)
4) 转换为递推式(自底向上)
publicstaticvoidmain(String[] args){ long start = System.currentTimeMillis(); int n = 50; long[] res = newlong[n]; res[0] = 1; res[1] = 1; for(int i = 2; i < n;i++){ res[i] = res[i - 1] + res[i - 2]; }
long end = System.currentTimeMillis() - start; System.out.println("time:"+end + "ms," + res[n -1]); }
House Robber(Leet code 198)
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.