Skip to content

Commit 047185c

Browse files
Add pseudo-code
1 parent 30ac674 commit 047185c

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

Pseudocode/DP/bottoms-up.txt

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
MAX_LIMIT
2+
CHOICE[C, D]
3+
4+
dp[CHOICE, MAX_LIMIT] = 0
5+
6+
for (d: CHOICE[0]) {
7+
dp[0, MAX_LIMIT - CHOICE[0, d]] = 1
8+
}
9+
10+
for (i = 1; i < CHOICE; ++i) {
11+
for (j = 0; j < MAX_LIMIT; ++j) {
12+
if (dp[i-1, j] == 1) {
13+
for (k = 0; k < D; ++k) {
14+
if (j - CHOICE[i][k] >= 0) {
15+
dp[i, j - CHOICE[i][k]] = 1
16+
}
17+
}
18+
}
19+
}
20+
}
21+
22+
// print 1 closest to 0.

Pseudocode/DP/top-down.txt

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
MAX_LIMIT
2+
CHOICE
3+
4+
memo[MAX_LIMIT, choice]
5+
6+
dp(cost, choice) {
7+
if (cost < 0) {
8+
return -inf;
9+
}
10+
11+
if (choice >= CHOICE) {
12+
return MAX_LIMIT - cost;
13+
}
14+
15+
if (memo[cost, choice] != -1) { // -1 implies not found
16+
return memo[cost, choice];
17+
}
18+
19+
ans = -1
20+
for (c : CHOICE[choice]) {
21+
ans = max(ans, dp(cost - CHOICE[c], choice + 1));
22+
}
23+
24+
return memo[cost, choice] = ans;
25+
}

0 commit comments

Comments
 (0)