2140. Solving Questions With Brainpower
my post
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 就可以
DP
從上面的 dfs 可以得到靈感
這個很 tricky, 開了一個超大的 dp array, 這樣就不用處理越界問題
處理邊界
T: O(n)
S: O(n)
Last updated
Was this helpful?