0

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?

varunkr
  • 5,364
  • 11
  • 50
  • 99

1 Answers1

1

Memoization can be performed as long as you're able to create a lookup structure that will recognize whether the arguments are the same so that you know when to return the previous result.

In Python a tuple is like a list except immutable and hashable so it can be used in a dictionary. In other languages you usually have to do a lot more work to create a lookup based on elements. What work that is depends on the language. With the most common fallback being to create a string representation of your arguments.

btilly
  • 43,296
  • 3
  • 59
  • 88