递归和金字塔

时间:2018-04-09 17:36:55

标签: java recursion

我正在进行一项实现递归的任务,并且很难理解如何通过重复进行此操作。

我需要能够检测数组是否有多个列/行然后计算每个的权重..

这就是它所说的:

The weight supported at each object is the weight of the object itself, plus 
half of the supported weight of the objects above it.

The weight supported by A is the weight of A itself.

The weight supported by B is the weight of B plus 1/2 the weight of A.

The weight supported by C is the weight of C plus 1/2 the weight of A.

The weight supported by E is the weight of E itself, plus 1/2 of the weight         
supported by B and 1/2 of the weight supported by C.

这是我到目前为止所做的,我测试了是否只有一个元素并将其返回:

public static double computePyramidWeights(double [][] weights, int row, int col){
    if (row == 0 && col == 0) {
        return weights[0][0];
    }

    return 1.0; //I know this should be where the recursive goes
}

鉴于前。像:

    A
  B    C
D    E    D

1 个答案:

答案 0 :(得分:0)

这依赖于我的假设,即金字塔在2D数组中的结构为{{A},{B,C},{D,E,F}},您没有指定。

public static double computePyramidWeights(double [][] weights, int row, int col){
    if (row < 0 || col < 0 || col >= weights[row].length) {
        return 0.0;
    }
    return weights[row][col]
            + 0.5 * computePyramidWeights(weights, row-1, col)
            + 0.5 * computePyramidWeights(weights, row-1, col-1);
}

请注意,此功能专注于计算,而不是验证输入。例如,如果此算法的调用者请求不存在的行的权重,则可能抛出异常。但是,抛出异常是一个非常合理的结果!为什么?因为它表示需要修复的编码错误,所以不应该不必要地掩盖程序员错误。

但是,如果您需要验证用户输入(例如,用户输入的列和行),可以(并且应该)使用单独的函数完成:

// demonstrate how to do a separate input validity check
public static boolean validRowCol(double [][] weights, int row, int col) {
    // return false if there is no such weights[row][col]
    return row >= 0 && col >= 0 && row < weights.length && col < weights[row].length;
}