数组的最小成本遍历

时间:2015-06-08 19:22:57

标签: c# arrays traversal

如何使用步和跳计算整数数组的最小成本遍历,同时还计算数组的第一个和最后一个元素?步骤正在移动到阵列中的下一个立即值,例如array [currentIndex + 1],跳跃正在移动两个点,例如array [currentIndex + 2]。我有以下函数,我想返回开始的最小总和,它将第一个和最后一个元素添加到总和中,但我仍然坚持数组的中间值。

An example of this would be {2, 10, 4, 14, 44, 28, 16, 18} -> 66
which would add indexes 0, 2, 3, 5, and 7.

====

public int Cost(int[] board)
{
    int sum = board[0];
    int index = 0;
    while (index < board.Length)
    {
        //Add the final array value to the sum
        if (index + 1 == board.length)
        {
            sum += board[index];
            break;
        }
        //Add other values here

        index++;
    }
    return sum;
}

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

    public int Cost(int[] board)
    {
        int[] cost = new int[board.Length];
        for (int i = 0; i < board.Length; i++) {
            if (i == 0) {
                cost[i] = board[0];
            } else if (i == 1) {
                cost[i] = board[1] + cost[0];
            } else {
                cost[i] = board[i] + Math.Min(cost[i - 1], cost[i - 2]);
            }
        }
        return cost[board.Length - 1];
    }

答案 1 :(得分:0)

一种可能的解决方案:

public int Cost(int[] board, int step = 1)
{
    if (board == null) return -1;
    if (board.Length == 0) return 0;

    // always add first and last index (if its not the first)
    int sum = board[0];

    if (board.Length > 1) sum += board[board.Length - 1];

    // assumes step is > 0
    for (int i = step; i < (board.Length - 1); i += step)
    {
        sum += board[i];
    }

    return sum;
}

这允许步骤为参数。也许现在你想要从一开始就走1或2。也许以后你想要走5个点。