从列表中查找最佳数字组合

时间:2016-02-10 16:11:43

标签: dynamic-programming

示例数据:

A = a set of 'things' denoted by integers {0,1,2,3,4,5,6,7,8,9}
B = value of "something" at each integer {23,33,54,12,45,66,21,23,44,77}
distance = the required distance between integers; 
//i.e. if distance = 2, you could choose 0 and 2 but not 1 and 2 - since (2 - 1 < 2)

So, AT 0, the value = 23
AT 1, the value = 33

因为看起来我脑子里很清楚......但是没有其他人让我试着更好地解释这个问题:

A = the 1 foot intervals from the start to the end.
B = the dollar amount you can pick up at a given interval
distance = the minimum distance you can travel between intervals. 

所以,如果你在开始时拿到23美元,你必须在第1区间跳过33美元。然后你可以在第2区间拿到54美元。

我想,你必须在每个时间间隔选择最好的$$$。

所以最好的是0,1然后最好的2,3等等(无论距离是多少)

但也许不是......因为如果1是第一个中最好的,而2是最好的,那么“最佳”方法会失败..

1 个答案:

答案 0 :(得分:1)

所以我使用下面的等式来计算动态编程中的opt值:

if (i -d) >= 0
opt(i) = max (opt(i-1), B[i] + OPT(i-d));

else 

opt(i) = max (opt(i-1), B[i]);

用于计算OPT值的Psuedo代码:

int A[] = {integers list}; // This is redundant if the integers are consecutive and are always from 0..n.
int B[] = {values list};
int i = 0;
int d = distance; // minimum distance between two picks.
int numIntegers = sizeof(A)/sizeof(int);

int opt[numIntegers];

opt[0] = B[0]; // For the first one Optimal value is picking itself.
for (i=1; i < numIntegers; i++) {

    if ((i-d) < 0) {
        opt[i] = max (opt[i-1], B[i]);
    } else {
        opt[i] = max (opt[i-1], B[i] + opt[i-d]);
    }

}