java循环最优解问题_Java数据结构算法问题,求最优解

public static List limitValSubsequence(int[] sequence, int limitValue) {

List retList = new ArrayList<>();

int[] sortSeq = Arrays.copyOf(sequence, sequence.length);

Arrays.sort(sortSeq);

int sumVal = 0;

int k = 0;

for (int i = sortSeq.length - 1; i >= 0; i--) {

sumVal += sortSeq[i];

if (sumVal > limitValue) {

k = sortSeq.length - i;

break;

}

}

if (k == 0) {

System.err.println("No subsequence math condition to > " + limitValue);

return retList;

}

limitValSubsequencePart(sortSeq, k, sequence.length - 1, limitValue, retList);

return retList;

}

public static int limitValSubsequencePart(int[] sequence, int count, int right, int limitValue,

List outSeq)

{

outSeq.clear();

if (count <= 0) return Integer.MIN_VALUE;       //不可选了

if (right 

int curVal = sequence[right];

if (limitValue > count * curVal) return Integer.MIN_VALUE;

if (right == 0) {

if (curVal > limitValue && count == 1) {

outSeq.add(curVal);

return curVal;

} else {

return Integer.MIN_VALUE;

}

}

//if curVal in

List curInSeq = new ArrayList<>();

int inValue = Integer.MIN_VALUE;    //预设无效

if (curVal > limitValue && count == 1) {

inValue = curVal;

curInSeq.add(curVal);

} else {

List inSubSeq = new ArrayList<>();

int subVal = limitValSubsequencePart(sequence, count - 1, right-1, limitValue - curVal, inSubSeq);

if (subVal == Integer.MIN_VALUE) {//无效

inValue = Integer.MIN_VALUE;

} else {

inValue = curVal + subVal;

curInSeq.addAll(inSubSeq);

curInSeq.add(curVal);

}

}

//if curVal not in

List curOutSeq = new ArrayList<>();

int outValue = limitValSubsequencePart(sequence, count, right-1, limitValue, curOutSeq);

if (inValue == Integer.MIN_VALUE) {

outSeq.addAll(curOutSeq);

return outValue;

} else if (outValue == Integer.MIN_VALUE) {

outSeq.addAll(curInSeq);

return inValue;

} else {

if (curInSeq.size() 

outSeq.addAll(curInSeq);

return inValue;

} else if (curInSeq.size() > curOutSeq.size()) {

outSeq.addAll(curOutSeq);

return outValue;

} else {

if (inValue > outValue) {

outSeq.addAll(curOutSeq);

return outValue;

} else {

outSeq.addAll(curInSeq);

return inValue;

}

}

}

}

public static void testLimitValArray() {

final int NUMBER = 150;

int[] inputs = new int[NUMBER];

for (int i = 0; i 

int limitValue = NUMBER * 10;

long startTime = System.currentTimeMillis();

List vals = limitValSubsequence(inputs,  limitValue);

int sumVal = 0;

for (int val : vals) sumVal += val;

long usedTime = System.currentTimeMillis() - startTime;

System.out.println("testLimitValArray limit:" + limitValue +  ", sum:" + sumVal + ", elems:" + vals + ", usedTime:" + usedTime);

}

testLimitValArray limit:1500, sum:1501, elems:[46, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150], usedTime:9565

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值