I want to know how to find the LIS of an array using Top Down Dynamic Programming. Does there exist one such solution? Can you give me the pseudocode for finding the LIS of an array using Top Down Dynamic Programming? I am not able to find one on the internet. All of them use Bottom Up.
Sure. Define:
F(n) = longest increasing subsequence of sequence 1..n , and the sequence must ends with elementn
Then we get that recursion function (Top down):
F(n) = max(len(F(i)) + 1) which 0 <= i < n and array[i] < array[n]
So the answer is:
Longest increasing subsequence of F(1..n)
With memoization, we come to this code(That's Python, it's better than pseudo-code):
d = {}
array = [1, 5, 2, 3, 4, 7, 2]
def lis(n):
if d.get(n) is not None:
return d[n]
length = 1
ret = [array[n]]
for i in range(n):
if array[n] > array[i] and len(lis(i)) + 1 > length:
length = len(lis(i)) + 1
ret = lis(i) + [array[n]]
d[n] = ret
return ret
def get_ans():
max_length = 0
ans = []
for i in range(len(array)):
if max_length < len(lis(i)):
ans = lis(i)
max_length = len(lis(i))
return ans
print get_ans() # [1, 2, 3, 4, 7]