Algorithm 摘要;爬楼梯“;允许用户输入允许步长增量的算法

Algorithm 摘要;爬楼梯“;允许用户输入允许步长增量的算法,algorithm,dynamic-programming,Algorithm,Dynamic Programming,在查看了这个通用函数之后,我开始怀疑是否可以将其抽象为一个函数,该函数允许输入楼梯数量和允许作为参数的最大增量步长 我想能够用这个签名写一个函数。如果max_step_increment为4,则表示爬楼梯者一次可以走1、2、3或4步 def stair_paths(num_steps, max_step_increment): ... return answer 我会像调用楼梯路径(10,4)一样调用此函数。让f[n]表示到达n个楼梯的所有允许步骤的方法数 最初,f[0]=1,

在查看了这个通用函数之后,我开始怀疑是否可以将其抽象为一个函数,该函数允许输入楼梯数量和允许作为参数的最大增量步长

我想能够用这个签名写一个函数。如果
max_step_increment
为4,则表示爬楼梯者一次可以走1、2、3或4步

def stair_paths(num_steps, max_step_increment):
    ...
    return answer

我会像调用楼梯路径(10,4)一样调用此函数。

让f[n]表示到达n个楼梯的所有允许步骤的方法数

最初,f[0]=1,其余的都是0

然后,f[i]=sigma(f[i-允许的步骤[j]]),其中允许的步骤[j]都是可能的允许步骤


最后的答案应该是f[numStairs],在你的例子中是f[10]。

用Java解决。如果您的方法声明是:

    int stairPaths(int numSteps, int maxStepIncrement)
正如您所定义的,以下是动态规划解决方案:

    int stairPaths(int numSteps, int... stepsAllowed)
    {
        if (stepsAllowed.length == 0) {
            return 0;
        }
        Arrays.sort(stepsAllowed);
        if (stepsAllowed[0] < 1) {
            throw new IllegalArgumentException("Invalid step increment " + stepsAllowed[0]);
        }
         int maxStepIncrement = stepsAllowed[stepsAllowed.length - 1];
        int[] priorElements = new int[maxStepIncrement];
        priorElements[maxStepIncrement - 1] = 1;
        priorElements[maxStepIncrement - 2] = 1;
        for (int i = 2; i <= numSteps; i++) {
            int nextElement = 0;
            for (int j = 0; j < stepsAllowed.length; j++) {
                nextElement += priorElements[maxStepIncrement - stepsAllowed[j]];
            }
            for (int k = 1; k < maxStepIncrement; k++) {
                priorElements[k - 1] = priorElements[k];
            }
            priorElements[maxStepIncrement - 1] = nextElement;
        }
        return priorElements[maxStepIncrement - 1];
    }
int stairPaths(int numSteps,int…stepsAllowed)
{
if(stepsAllowed.length==0){
返回0;
}
Arrays.sort(stepsAllowed);
如果(步数小于[0]<1){
抛出新的IllegalArgumentException(“无效步长增量”+stepsAllowed[0]);
}
int maxStepIncrement=stepsAllowed[stepsAllowed.length-1];
int[]prioreelements=新的int[maxStepIncrement];
主元素[maxStepIncrement-1]=1;
主元素[maxStepIncrement-2]=1;
对于(int i=2;i