Question 6 Longest Increasing Subsequence母体
Method 1暴力解(从后往前,但是不会用在面试中,只是为了训练)
public int longest(int[] array) {
// assume array valid
int[] longest = new int[]{1};
int currentLength = 0;
dfs(longest, currentLength, array, array.length - 1, null);
return longest[0];
}
private void DFS(int[] longest, int currentLength, int[] array, int index, Integer lastAddedValue) {
// 哪里都是解
longest[0] = Math.max(longest[0], currentLength);
// branch 所有在index之前比加过的第一个元素还要小的元素,我要知道上次加了谁?
for (int i = index; i >= 0; i++) {
if (lastAddedValue == null || array[i] < lastAddedValue) {
dfs(longest, currentLength + 1, array, array.length - 1, array[i]);
}
}
}Method 2 从backtracking 到pure recursion
Method 3 从pure recursion to recursion memo
Method 4真的确定有优化, pure recursion memo to dynamic programming
Last updated