时间复杂度
举例:
1.1到100的递归求和的时间复杂度
public static void main(String[] args) { int result = sum(9); System.out.println(result); } public static int sum(int k) { int sum = 0; if (k > 1) { sum = k + sum(k - 1); } else { sum = 1; } return sum; }
总结就是:当k大于1时,sum = sum(k-1)+k;当k等于1时,sum=1;即计算了k+k-1+k-2+...+1,等差数列,时间复杂度为O(K^2);
2.斐波那契数列的时间复杂度
代码略,思路:当k等于1和2时,f(k)=1;当k大于2时,f(k)=f(k-1)+f(k-2);根据二次线性齐次递推关系得:
[(1+√ ̄5)/2]^2,则时间复杂度为O([(1+√ ̄5)/2]^2),二次线性齐次递推举例:
Ride the wave as long as it will take you.