【问题标题】:finding the subset with the nearest value to the target if the algorithm find no subset that has the exact sum using stack如果算法使用堆栈找不到具有精确总和的子集,则找到与目标值最接近的子集
【发布时间】:2016-07-24 15:33:31
【问题描述】:
private static Stack<Integer> temp = new Stack<Integer>();

public void populateSubset(int[] DATA, int fromIndex, int endIndex, int target) {

    if (sumInStack == target) {
        check = true ;
        Counter ++ ;
        print(stack, target);
    }


    for (int currentIndex = fromIndex; currentIndex < endIndex; currentIndex++) {

        if (sumInStack + DATA[currentIndex] <= target) {
            stack.push(DATA[currentIndex]);
            sumInStack += DATA[currentIndex];
            if (sumInStack >= MaxSumInStack){
                    temp = stack;      
                    MaxSumInStack = sumInStack;

            }

            populateSubset(DATA, currentIndex + 1, endIndex, target);
            sumInStack -= (Integer) stack.pop();

        }
    } 
}

在java中的subsetSum算法中,如果算法找不到具有精确总和的子集,我想找到与目标值最接近的子集。 每次更新 sumInsStack 时,我都会存储堆栈和总和以找到最大总和。但最后临时堆栈为空,其中没有任何内容,尽管在每一步中它都会获得价值。我应该怎么办? P.S:我还想打印所有具有最大值的堆栈。

【问题讨论】:

  • stack 声明在哪里?

标签: java find stack nearest-neighbor subset-sum


【解决方案1】:

如果通过

temp = stack;

您打算复制Stack,这不是您正在做的事情。您只需使temp 变量与stack 变量引用相同的Stack,因此您稍后清空stack,同时也清空temp

为了进行复制,您必须将原始堆栈的元素显式复制到temp 堆栈:

temp = new Stack<Integer>();
temp.addAll(stack);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多