0

I was looking at this question on the usage of matrices in top down dynamic programming. In an attempt to apply it I tried the Longest Increasing Subsequence problem.

Looking at various implementations of the top down approach people seem to use a 1D array to memoize instead of a matrix. I thought the implementation would be a matrix where columns are the number of subproblems (which is the length of the array of numbers), and the number of rows would be the subset of remaining elements you can select from which at max would again be the length of the array of numbers - 1).

e.g.

   dp = [[1] * len(nums) for i in range(len(nums))]

How do you know when to use a matrix vs. 1D array in dynamic programming?

Paul
  • 1,101
  • 1
  • 11
  • 20
  • 1
    based on how many steps back you need to look in each direction. If it's enough to look back 2 steps, why keep a whole array? If it's enough to look back one row, why keep a whole grid? – user1984 Dec 08 '21 at 17:00
  • 1
    In simple terms, We can say the number of parameters in the states will be your dimension. – starboy_jb Dec 08 '21 at 17:01
  • @starboy_jb does sorry, could you clarify the number of parameters in the states? I'm not sure what that refers to. – Paul Dec 08 '21 at 17:16
  • "implementations of the top down approach" do you mean bottom-up? – ggorlen Dec 08 '21 at 17:19
  • @ggorlen no, I was looking at the top down approach. Bottom up was more intuitive for me so I've been trying to understand the top down memoization approach – Paul Dec 08 '21 at 17:23
  • `dp = [[1] * len(nums) for i in range(len(nums))]` is bottom-up. For top down, I've usually seen dicts/hashes/associative arrays/maps used to lookup parameters rather than arrays/lists. Can you share links to the LIS implementations you're talking about? Maybe that would clear up the confusion. – ggorlen Dec 08 '21 at 17:27
  • @ggorlen yeah, I was looking at this top down one: https://www.techiedelight.com/longest-increasing-subsequence-using-dynamic-programming/ – Paul Dec 08 '21 at 17:34
  • They don't show any top-down DP (memoization) code there. It's all bottom-up DP -- "we can also solve this problem in a bottom-up manner" [DP code ensues for the remainder of the article...]. I think there may be some terminology confusion here. – ggorlen Dec 08 '21 at 17:37
  • er, sorry. Wrong article: https://www.callicoder.com/longest-increasing-subsequence/ – Paul Dec 08 '21 at 17:48
  • Generally speaking (not specifically in the frame of DP), the choice can depend on the sparsity of the matrix, i.e. the number of entries effectively used. For instance, a 1000 x 1000 matrix could be a waste if only 3000 entries are used. –  Dec 08 '21 at 19:13

0 Answers0