I'm solving basic dynamic programming question. It's simple. input is single integer. if input is 3, all possible cases is 3,1+2,2+1,1+1+1 so out put is 4. if input is 4, output is 7 because 4 = 1+1+1+1 1+1+2 1+2+1 2+1+1 2+2 1+3 3+1. code above is my code to solve this.

use strict; use warnings; our @cache; sub find { my $num = shift; if(defined $cache[$num]) {return $cache[$num];} if($num == 0) {return 1;} if($num < 0) {return 0;} $cache[$num] = &find($num -1) + &find($num - 2) + &find($num - 3); return $cache[$num]; } my $test_case = <>+0; for(1..$test_case) { my $num = <>+0; print &find($num),"\n"; }

but the output is wrong. and I found that output of 2 is 3, instead of 2. also output of 3 is 5 instead of 4. to fix this, I write @cache1..3 = (1,2,4); and of course, It is fixed. But, I want to remove @cache1..3 = (1,2,4); and want to know why my original code is not working properly. when call solution(2), isn't it obvious that the output is solution(1) + solution(0) + solution(-1)? and when I call solution(0), solution(1), solution(-1) individually, the output is 1,1,0 so sum is 2. not 3. Thank you for your help.


In reply to problem while solving basic dynamic programming question by yujong_lee

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.