-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDyanmicPrograming.html
More file actions
142 lines (132 loc) · 2.84 KB
/
Copy pathDyanmicPrograming.html
File metadata and controls
142 lines (132 loc) · 2.84 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DP</title>
</head>
<body>
<script>
//Fibonacci subquence
//递归版本(复杂度很高O(2^n))
/*let arr = [];
function fab(n) {
if(n<2){
return 1;
}
return fab(n-1) + fab(n-2);
}
function sequence(n) {
for(let i = 0;i<n;i++){
arr[i] = fab(i);
}
console.log(arr);
}
sequence(10);*/
//非递归版本(复杂度为O(n))
/*let arr = [];
function fab(n) {
arr[0] = 1;
arr[1] = 1;
if(n>=2){
for(let i = 2;i<n;i++){
arr[i] = arr[i-1]+arr[i-2];
}
}
return arr;
}
console.log(fab(100));*/
let task = [
{
index: 1, money: 5, time: {
min: 1,
max: 4
}
},
{
index: 2, money: 1, time: {
min: 3,
max: 5
}
},
{
index: 3, money: 8, time: {
min: 0,
max: 6
}
},
{
index: 4, money: 4, time: {
min: 4,
max: 7
}
},
{
index: 5, money: 6, time: {
min: 3,
max: 8
}
},
{
index: 6, money: 3, time: {
min: 5,
max: 9
}
},
{
index: 7, money: 2, time: {
min: 6,
max: 10
}
},
{
index: 8, money: 4, time: {
min: 8,
max: 11
}
}
];
let prev;
function genPrev(n) {
if (n <= 1) return 0;
let minTime = task[n - 1].time.min;
for (let i = n - 2; i >= 0; i--) {
if (task[i].time.max <= minTime) {
prev = task[i].index;
return prev;
}
}
prev = 0;
return prev;
}
let opt;
//递归版本
function rec_optimal(n) {
if (n === 0) return 0;
if (n === 1) {
opt = task[0].money;
return opt;
}
for (let i = 2; i <= n; i++) {
let Unselect = rec_optimal(i - 1);
let Select = task[i - 1].money + rec_optimal(genPrev(i));
opt = Math.max(Unselect, Select);
}
return opt;
}
//非递归版本(动态规划)
function dp_optimal(n) {
let opt = [];
opt[0] = task[0].money;
for (let i = 1; i < n; i++) {
let Unselect = opt[i - 1];
let val = genPrev(i + 1) === 0 ? 0 : opt[genPrev(i)];
let Select = task[i].money + val;
opt[i] = Math.max(Unselect, Select);
}
return opt[n-1];
}
console.log(rec_optimal(8));
console.log(dp_optimal(8));
</script>
</body>
</html>