【发布时间】: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