my post
https://leetcode.com/problems/solving-questions-with-brainpower/discuss/1693386/Java-DFS-%2B-memo-and-DP-Solutions-or-T%3A-O(n)-S%3A-O(n)
DFS + memo
solution 1
use start end as key
class Solution {
public long mostPoints(int[][] questions) {
Map<String, Long> map = new HashMap<>();
return helper(questions, 0, questions.length - 1, map);
}
private long helper(int[][] questions, int start, Map<String, Long> map) {
if (start > end) {
return 0;
}
String key = start + "," + end; // use start, end as key
if (map.containsKey(key)) {
return map.get(key);
}
long cur = questions[start][0] + helper(questions, start + questions[start][1] + 1, end, map);
long next = helper(questions, start + 1, end, map);
long res = Math.max(cur, next);
map.put(key, res);
return map.get(key);
}
}
ๅ
ถๅฏฆๅช่ฆๅฐ start ็ด้ๅฐฑๅฅฝ, ๅ ็บๅบๅฎ start ็ฎๅบ็็ตๆๆฏไธๆจฃ็, ๅชๆฏไนๅพ้่ค่ทๆ, ๆ็จๅฐ, ๆไปฅๅฏไปฅๅ memo
ex : [1,2,3,4]
fix index 1, ๅฆๆๆฏ skip 1 index(skip index 2), ๆไปฅ 3 ๆ่จ็ฎ้
ไนๅพ fix index 2, ๅ่จญไธ่ทณ้ไปปไฝ index, ่ฆ็ฎ 3 ๆ, memo ๅฐฑๆไบๅผไบ, ๅฏไปฅๅฉ็จ
solution 2
ๆไปฅ้่ฃก็จ start ็บ key, ๆไปฅ็จไธๅ long array ๅฐฑๅฏไปฅ
class Solution {
public long mostPoints(int[][] questions) {
Long[] memo = new Long[questions.length];
return dfs(questions, 0, memo);
}
private long dfs(int[][] questions, int start, Long[] memo) {
if (start >= memo.length) {
return 0;
}
if (memo[start] != null) {
return memo[start];
}
long cur = questions[start][0] + dfs(questions, start + questions[start][1] + 1, memo);
long next = dfs(questions, start+1, memo);
memo[start] = Math.max(cur, next); // just use start as key, ya it works.
return memo[start];
}
}
DP
ๅพไธ้ข็ dfs ๅฏไปฅๅพๅฐ้ๆ
dp[i] = Math.max(
questions[start][0] + dp[start + questions[start][1] + 1],
dp[i+1]
);
ๅ ็บ็จๅฐ dp[i+1], ๆไปฅๅพๅพ้ข for loop
้ๅๅพ tricky, ้ไบไธๅ่ถ
ๅคง็ dp array, ้ๆจฃๅฐฑไธ็จ่็่ถ็ๅ้ก
class Solution {
public long mostPoints(int[][] questions) {
int n = questions.length;
long[] dp = new long[200001];
for (int i = n - 1; i >= 0; i--) {
dp[i] = Math.max(
questions[i][0] + dp[i + questions[i][1] + 1],
dp[i+1]
);
}
return dp[0];
}
}
่็้็
T: O(n)
S: O(n)
class Solution {
public long mostPoints(int[][] questions) {
int n = questions.length;
long[] dp = new long[n+1];
for (int i = n - 1; i >= 0; i--) {
int curIdx = i + questions[i][1] + 1;
long curValue = (curIdx >= n) ? 0 : dp[curIdx];
dp[i] = Math.max(questions[i][0] + curValue, dp[i+1]);
}
return dp[0];
}
}