题目:
思路
①暴力递归,但这样时间复杂度是O(n)
②递归快速幂:拆解2^n = 2^(n/2) * 2^(n/2),这样时间复杂度是O(log(n))
代码:
class Solution {
public double myPow(double x, int n) {
if(n < 0){//负次幂的情况
x = 1 / x;
n = Math.abs(n);
}
return count(x, n);
}
public double count(double x, int n) {
if(n == 0)
return 1;
double half = count(x, n/2);
if(n % 2 == 0){
return half * half;
}
else
return half * half *x;
}
}
复杂度分析:
时间复杂度:O(log(n))
空间复杂度:O(log(n))