总结

找重复
1.找到一种划分方法
2.找到递推公式或者等价转换,都是父类问题转换为子类问题

找变的量
变化的量通常作为参数

找出口

所有的循环都可以改成递归

源代码

package shuyan1;
//设计一个高效的求a的n次幂的算法
public class e {
//	普通算法  
//	时间复杂度:O(N)
	private static int pow0(int a ,int n) {
		int res=1;
		for (int i = 0; i < n; i++) {
			res*=a;
		}
		return res;
	}
//	高效算法
/*	2 2 2 2 2 2 2 2 2 2
 * 	第一次:2*2
 * 	第二次:4*4  或  (2*2)*(2*2)
 * 	第三次:16*16   或  (2*2*2*2)*(2*2*2*2)
 * 	第四次:256*2*2  或  256*(2*2)
 */
//	时间复杂度: O(log2 N)
	private static int pow(int a,int n) {
		if(n==0) return 1;
		int res=a;
		int ex=1;
		while((ex<<1)<=n) {
			res*=res;
			ex<<=1;
		}
		return res*pow(a,n-ex);
	}
	public static void main(String[] args) {
		// TODO Auto-type name = new type();generated method stub
		System.out.println(pow0(2,10));
		System.out.println(pow(2,10));
	}

}

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐