巧用数学的思想来解决程序算法问题,这样的代码如诗般优美。通过数学思想来看问题,也能将程序简单化。“斐波那契数列”对于java程序员来说一定不陌生。当然这个问题的解决方案也有很多。用一个例子说明数学思想的优越性。
题例:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
传统方法:用三个变量实现。如:
|
1
2
3
4
5
6
7
8
9
|
public static int oneMethod() { int a = 1, b = 0, c = 0; for (int i = 1; i <= 12; i++) { c = a + b; a = b; b = c; } return c;} |
递归实现:
|
1
2
3
4
5
6
7
8
9
|
public static int twoMethod(int index) { if (index <= 0) { return 0; } if (index == 1 || index == 2) { return 1; } return twoMethod(index - 1) + twoMethod(index - 2);} |
用数学思想来解决问题,就相当于找规律。因为“斐波那契数列”并不是没有规律可循。对于这个数列都满足通用公式:Fn=F(n-1)+F(n-2)(n>=2,n∈N*),直接循环一次就可以得到结果,相比于递归和第一种方式是不是简单的多,而且递归次数过多的话,性能也很受影响。
数学方式实现:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public static int threeMethod(int index) { if (index <= 0) { return 0; } if (index == 1 || index == 2) { return 1; } int[] tuZiArray = new int[index]; tuZiArray[0] = 1; tuZiArray[1] = 1; for (int i = 2; i < tuZiArray.length; i++) { tuZiArray[i] = tuZiArray[i - 1] + tuZiArray[i - 2]; } return tuZiArray[index - 1];} |
虽然上面三种方法得到的结果都一样,但是我觉得一个程序的好与不好区别在算法。递归也不是不好,只是具体问题的使用场景不同。程序要尽量简单化,而代码也要有精简之美。小小拙见,希望对大家有所帮助。