序言:
问楼梯问题时,通常给定的允许步速数组为[1,2,3]
查看关于SO的同一问题的许多示例,例如 n-steps-with-1-2-or-3-steps-taken-how-many-ways-to-get-to-the-top
我的问题与此有关,但是是在为允许的步伐包括负数和零的情况下寻找证据。
诸如此类的明显事物
示例:
countSteps(stairSize:=5, [ 1,2,3]) // 17
countSteps(stairSize:=5, [0,1,2,3]) // 17...
countSteps(stairSize:=5, [-2,-1 ]) // zero ways
countSteps(stairSize:=5, [-2,-1,0]) // infinitely zero ways
countSteps(stairSize:=5, [2,4]) // zero ways
countSteps(stairSize:=5, [ 3]) // zero ways
countSteps(stairSize:=5, [-1,3]) // infinite ways
countSteps(stairSize:=5, [6,7,8]) // zero ways
问题:
? Can you determine whether given
a stair size (1.. for now)
and an array of allowable steps
is the result find-able ?
答案 0 :(得分:0)
您可以分为两个部分:
private int getNumWaysToReachStep(
final int targetStep,
final boolean[] isStepReachable,
final int[] numWaysToReachStep,
final int[] numStepsAtATimeArr) {
if (targetStep == 0) {
return 1;
} else if (targetStep < 0 || targetStep >= isStepReachable.length) {
return 0;
} else if (numWaysToReachStep[targetStep] != 0 || ! isStepReachable[targetStep]) {
return numWaysToReachStep[targetStep];
}
int result = 0;
for (final int numSteps : numStepsAtATimeArr) {
result += getNumWaysToReachStep(targetStep - numSteps, isStepReachable,
numWaysToReachStep, numStepsAtATimeArr);
}
numWaysToReachStep[targetStep] = result;
return result;
}
)总体而言,这需要 O ( stairSize ·|| numStepsAtATimeArr |)时间和 O ( stairSize )多余的空间。