-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicProgramDemo1.java
More file actions
78 lines (62 loc) · 2.01 KB
/
DynamicProgramDemo1.java
File metadata and controls
78 lines (62 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package node;
public class DynamicProgramDemo1 {
/**
* 找出数组里面 各种数字
* 数组 arr = {1,2,4,1,7,8,3};
*
*
* 1)选一些 不相临 的数字, 可选多个数字
* 2)选好的这些数字 相加, 得出最大值
*
* @param args
*/
public static void main(String[] args) {
//int[] arr = {1,2,4,1,7,8,3};
//int[] arr = {4,1,1,9,1};
int[] arr = {6,3,8,9,1};
System.out.println(recursion_opt(arr,4));
System.out.println(dynamicPro_opt(arr));
}
/**
* 使用 递归 来解决这个问题
*
* @param arr
* @param arrIndex
* @return
*/
public static int recursion_opt(int[] arr, int arrIndex){
int x = arrIndex;
int A; // chose current position scenario
int B; // not chose this current position scenario
// 写递归, 首先 写退出 递归的条件
if (x==0){ // 当 index 是 0 的时候, 取 arr[0], 返回值
return arr[0];
}else if (x==1){
return Math.max(arr[0], arr[1]); // 当 index 是 1 , 去 前面两个 数, arr[0] , arr[1] 的最大值
}else {
A = recursion_opt(arr,x-2) + arr[x]; // A 情况, 当选当前 数字, arr[current] , 递归
B = recursion_opt(arr, x-1);
return Math.max(A,B);
}
}
/**
* 使用 非递归的方法
*
* @param arr
*
* @return
*/
public static int dynamicPro_opt(int[] arr){
int[] opt = new int[arr.length];
int A; // chose current position scenario
int B; // not chose this current position scenario
opt[0] = arr[0];
opt[1] = Math.max(arr[0], arr[1]);
for (int i = 2; i < arr.length; i++) {
A = opt[i-2] + arr[i];
B = opt[i-1];
opt[i] = Math.max(A,B);
}
return opt[arr.length-1];
}
}