Implement pow(x, n).
实现x的n次方
x * x * … * x
递归:x^n = x^(n-1) * x 时间复杂度:o(n)栈溢出了
递归:x^n = x^(n/2) * x^(n-n/2) 但是我觉得这个其实也是log(n)啊
因为分解的子问题的层数是logn 但是底层有2^logn个子问题 求解最底层的问题是时间复杂度就是o(n)了吧超时了
难道不是这样吗?。。。。
这个应该找个大神确认一下。。别弄错了。。
总之:
递归的话两种都差不多 一个子问题多层数logN 一个子问题少层数N
动态规划的话都是得每个遍历 因为不知道后面要用到哪个 那样就没差别了
还想到一个 参考之前的除法那道题目:
动态规划只保留x x^2 x^4 x^8…..
然后比如x^9
x^1 (1 剩余8)
x^2 (3 剩余5)
x^4 (7 剩余2)
x^1 (8 剩余1)
x^1 (9 剩余0)
可以A的
public double myPow(double x, int n) {
return myPow(x, (long)n);
}
public double myPow(double x, long n) {
if (n == 1)
return x;
else if(n == 0)
return 1;
else if(n > 0){
//1.普通递归分解为n-1 x 栈溢出
//return x*myPow(x, n-1);//java.lang.StackOverflowError
//2.分解为n/2 和 n-n/2 超时
//return myPow(x, n/2) * myPow(x, n-n/2);//Time Limit Exceeded
//3.分解为 n/2 n/2 (x) AC
double half = myPow(x, n/2);
if (n % 2 == 0) return half*half;
else return half*half*x;
}
else
return 1.0 / myPow(x, -n);
}
还有一个做法 思路借鉴除法那道题:
public double myPow(double x, long n) {
double result = 1;
if(n == 0) return 1;
if(n == 1) return x;
if(n < 0 ) return 1.0/myPow(x, -n);
double[] dp = new double[(int)(Math.log(n)/Math.log(2))];
for(int i = 0;i <(int)(Math.log(n)/Math.log(2));i++)
dp[i] = Math.pow(x,(int)Math.pow(2, i));
int index = 0;
while(n > 0){
result *= dp[index];
n -= Math.pow(2, index);
if(n > Math.pow(2, index+1)) index++;
else index = 0;
}
return result;
}
也是AC的