【问题标题】:How can I implement backtracking for a climbing stairs practice in JS? [duplicate]如何在 JS 中实现爬楼梯练习的回溯? [复制]
【发布时间】:2018-01-21 04:58:06
【问题描述】:

我无法在函数中实现回溯。我有一个来自我will link here 的代码战的问题。

你需要爬一个有 n 级台阶的楼梯,你决定通过跳上台阶来做一些额外的锻炼。一次跳跃最多可以走 k 步。返回你爬楼梯的所有可能的跳跃序列,排序。

对于 n = 4 和 k = 2,输出应为:

climbingStaircase(n, k) = [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2]]

我应该以回溯的心态来解决这个问题,但回溯对我来说是新事物,我很难在函数中实现它。我觉得我快到了边缘,但只需要一点推动。我该如何解决这个问题并完全理解回溯?

【问题讨论】:

  • 我敢打赌更好的标题将是一个好的开始?
  • 有什么建议吗?

标签: javascript dynamic-programming backtracking


【解决方案1】:

我遇到了同样的问题,但我解决了。这是Java中的解决方案:

    ArrayList<int[]> solutions = new ArrayList<int[]>();

    int[][] climbingStaircase(int n, int k) {
        climb(new int[n*k], 0, 0, 0, n, k);
        return trimSolution(solutions);
    }

    void climb(int[] sol, int index, int step, int sum, int max, int stepMax) {
        if(step != 0) {
            sum += step;
            sol[index++] = step;
            if(sum < max) {
                // printArray("it: ", sol);
            } else if(sum == max){
                // printArray("sol: ", sol);
                solutions.add(trimSolution(sol));
                sol[--index] = 0;
                return;
            } else {
                sol[--index] = 0;
                // printArray("failed: ", sol);
                return;
            }
        }

        for (step = 1; step <= stepMax; step++) {
            // System.out.println("index: " + index);
            climb(sol, index, step, sum, max, stepMax);
        }
    }

    int[] trimSolution(int[] sol) {
        int length = 0;
        for (int i = 0; i < sol.length; i++) {
            if(sol[i] != 0)
                length++;
        }
        int[] r = new int[length];
        for (int i = 0; i < r.length; i++) {
            r[i] = sol[i];
        }
        return r;
    }

    int[][] trimSolution(ArrayList<int[]> sol) {
        if(sol.size() == 0)
            sol.add(new int[0]);
        int[][] r = new int[sol.size()][1];
        for (int i = 0; i < sol.size(); i++) {
            r[i] = sol.get(i);
        }
        return r;
    }

void printArray(String message, int[] a) {
    System.out.print(message);
    for (int i = 0; i < a.length; i++) {
        System.out.print(a[i] + ", ");
    }
    System.out.println();
}

【讨论】:

  • 转储代码没有帮助,请解释一下。有时,代码只是证明某人有互联网连接;解释表明你自己理解答案,并且足够体贴地解释它。
猜你喜欢
  • 1970-01-01
  • 2021-12-18
  • 2015-05-29
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
相关资源
最近更新 更多