I am reading about dynamic programming and was trying to solve the Longest Increasing subsequence problem.
I tried to come up with a brute force recursion approach where I generated all possible increasing subsequences and checked which one is the longest.
private int lis(int[] arr, int k, List<Integer> curr){
int ans = 0;
for(int i=k;i<arr.length;i++){
if(!curr.isEmpty() && arr[i]<=curr.get(curr.size()-1)){
continue;
}
curr.add(arr[i]);
ans = Math.max(ans, curr.size());
ans = Math.max(ans,lis(arr,i+1,curr));
curr.remove(curr.size()-1);
}
return ans;
}
Here arr
is the input array, k
is 0 and curr
is a list where I store the current increasing subsequence, ans
is a global variable that keeps count of the longest increasing subsequence. I get TLE on this solution which is expected.
I know that this isn't the most efficient approach since I am using a list to keep track of elements and the problem can be solved without it. But I was still trying to apply memoization to this code as an exercise.
I'm trying to understand if memoization can be applied to any recursive brute force solution (or does it require the recursive solution to be in a specific format since there are several types of recursions like tail recursion etc)? If no what properties should it satisfy?
Can memoization be applied to the above algorithm to make it work?