题目描述:
Implement pow(x, n). 难度 Medium
解题思路:利用分治法(Divide and Conquer),对n进行划分,如果n为偶数,那么可以先求出x^(n/2) ,得到结果后对其求平方,即可得到x^n=x^(n/2) * x^(n/2). 如果n为奇数,则x^n=x^((n-1)/2)*x^((n-1)/2)*x. 这样一来一个规模为n的问题,就可以变成规模为n/2的子问题,通过递归调用,直到n=0时返回1或者在n=1的时候返回x. 考虑到n有可能为负数,要对以上的算法进行一些修改:
n为正整数的时候按照如上思路,如果为负数,则n为奇数的情况下,x^n=x^((n+1)/2)*x^((n+1)/2)*x,递归直到n=-1的时候返回1/x,最后的结果还要再除以x。
时间复杂度为O(logn),小于线性时间复杂度。
由于一开始没有考虑到n可以是负数,所以造成了错误,代码也写得不够简洁。
class Solution {
public:
double myPow(double x, int n) {
double ans;
if(n==0)
return 1;
if(n==1)
return x;
if(n==-1)
return 1/x;
double h;
if(n%2==0)
h=myPow(x,n/2);
else if(n>0)
h=myPow(x,(n-1)/2);
else if(n<0)
h=myPow(x,(n+1)/2);
h*=h;
if(n%2==0)
return h;
else if(n>0)
ans=h*x;
else if(n<0)
ans=h/x;
return ans;
}
};