さて、これがコードが行うことです。
`if (n<0)`
`return 0;`
十分なステップが残っていない場合は、カウントしないでください。たとえば、あと 2 ステップあるが、ユーザーが 3 つのステップを実行しようとしている場合、それは可能な組み合わせとしてカウントされません。
else if (n==0)
return 1;
残りのステップ数が、ユーザーが実行しようとしている使用可能なステップ数と一致する場合、それは可能な組み合わせです。したがって、これは可能な組み合わせであり、有効な組み合わせの総数に追加する必要があるため、1 を返します。
else if (map[n]>-1)
return map[n];
これが動的計画法の部分です。配列内のすべての値の値が -1 であると仮定します。したがって、数値が -1 より大きい場合は、既に解決されているため、解決する代わりに、ステップ番号 n からの組み合わせの総数を返します。
`map[n] = countDP(n-1, map) + countDP(n-2, map) + countDP(n-3, map);`
return map[n]; }
最後に、この部分でコードを解決します。可能な組み合わせの数は、ユーザーが 1 ステップ実行した場合に取得できる可能な組み合わせの数 + ユーザーが 2 ステップ実行した場合に取得できる可能な組み合わせの数 + ユーザーが実行した場合に取得できる可能な組み合わせの数に等しい3 つのステップ。
例として、5 つのステップがあるとします。
簡単な実行は次のようになります。
//The number of solutions from the fifth step
countDp(5) = countDp(4)+countDp(3)+countDp(2);
//Number of solutions from the fourth step
countDP(4) = countDp(3)+countDp(2)+countDp(1);
//Number of solutions from the third step
countDp(3) = countDp(2)+countDp(1)+countDp(0);
//Number of solutions from the second step
countDp(2) = countDp(1)+countDp(0)+countDp(-1);
//Number of solutions from the first step
countDp(1) = countDp(0) + countDp(-1)+countDp(-2);
//Finally, base case
countDp(0) = 1;
countDp(-1)= 0;
countDp(-2)= 0;
countDp(1) = 1+0+0 = 1;
countDp(2) = 1+1+0 = 2; //Dynamic programming: did not have to resolve for countDp(1), instead looked up the value in map[1]
countDp(3) = 2+1+1 = 4; //Dynamic programming, did not have to solve for countDp(1), countDp(2), instead looked up value in map[1] and map[2]
countDp(4) = 4+2+1=7 //Dynamic programming, did not have to solve for CountDp(3),CountDp(2), CountDp(1), just looked them up in map[3],map[2],map[1]
countDp(5)= 2+4+7=13 //Dynamic programming, just used map[4]+map[3]+map[2]