好的,这就是代码的作用。
`if (n<0)`
`return 0;`
如果剩余的步数不够,就不要算了。例如,如果还剩两步,但用户尝试走三步,则它不算作可能的组合。
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 步可获得的可能组合数量 + 用户走 2 步可获得的可能组合数量三个步骤。
举个例子,假设有 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]