1、斐波那契数列

/**
* 求斐波那契数列的第 n 项,n <= 39。
*/
public class Solution {
public static void main(String[] args) {
System.out.println(new Solution().Fibonacci(4));
}

public int Fibonacci(int n) {
if (n <= 2) {
return 1;
}
return Fibonacci(n - 1) + Fibonacci(n - 2);
}

public int Fibonacci2(int n) {
if (n <= 2) {
return 1;
}
int pre1 = 1, pre2 = 2, result = 3;
for (int i = 3; i < n; i++) {
result = pre1 + pre2;
pre1 = pre2;
pre2 = result;
}
return result;
}
}

2、跳台阶

/**
* 一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。
*
* @author maxinze
*/
public class Solution {
public static void main(String[] args) {
System.out.println(new Solution().jumpFloor(5));
}

public int jumpFloor(int target) {
if (target <= 2)
return target;
int pre1 = 1, pre2 = 2, result = 0;
for (int i = 3; i < target; i++) {
result = pre1 + pre2;
pre1 = pre2;
pre2 = result;
}
return result;
}
}

3、连续子数组的最大和

public class Solution {
public static void main(String[] args) {

}

public int FindGreatestSumOfSubArray(int[] array) {
int[] dp = new int[array.length];
int max = array[0];
dp[0] = array[0];
for (int i = 1; i < array.length; i++) {
// 动态规划,状态转移方程,确定dp[i]的最大值
dp[i] = Math.max(dp[i - 1] + array[i], array[i]);
// 每次比较,保存出现的最大值
max = Math.max(max, dp[i]);
}
return max;
}
}