Integer[] datas = new Integer[]{1,2,3,4,5,6,7,8,9,10,11};//目标数组Integer min = 6;//大于等于的值Integer max = 12;//小于等于的值Integer count = 3;//指定数量根据count如:3,3个数相加大于等于min小于等于max,2个数相加大于等于min小于等于max,1个数相加大于等于min小于等于max。如果count=2,2个........,1ge.........。返回List。下面代码是我写死,我想知道怎样写活【count】public static void main(String[] args) {
Integer[] datas = new Integer[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
Integer min = 6;
Integer max = 12;
Integer count = 3;
List<Integer[]> test = test(datas, min, max, count);
for(Integer[] integers : test){
for(Integer t : integers){
System.out.print("["+t+"]");
}
System.out.println("");
}
}
public static List<Integer[]> test(Integer[] datas, Integer min, Integer max, Integer count){
List<Integer[]> result = new ArrayList<>();
switch (count){
case 1:
result.addAll(one(datas, min, max));
break;
case 2:
result.addAll(one(datas, min, max));
result.addAll(two(datas, min, max));
break;
case 3:
result.addAll(one(datas, min, max));
result.addAll(two(datas, min, max));
result.addAll(three(datas, min, max));
break;
}
return result;
}
public static List<Integer[]> one(Integer[] datas, Integer min, Integer max){
List<Integer[]> result = new ArrayList<>();
for(int i = 0,len = datas.length; i < len; i++){
if(datas[i] >= min && datas[i] <= max){
result.add(new Integer[]{i});
}
}
return result;
}输出的【下标】组合[5]
[6]
[7]
[8]
[9]
[10]
[11]
[0][4]
[0][5]
[0][6]
[0][7]
[0][8]
[0][9]
[0][10]
[1][3]
[1][4]
[1][5]
[0][1][2]
[0][1][3]
[0][1][4]
[0][1][5]
[0][1][6]
[0][1][7]
[0][1][8]
[0][2][3]
[0][2][4]
[0][2][5]
[0][2][6]
[0][2][7]
[0][3][4]
[0][3][5]
5 回答

慕尼黑8549860
TA贡献1818条经验 获得超11个赞
这个是我老早以前,好像看一本<<妙趣横生的算法>>里面学的。其实这个算法时间复杂度有点高。你要学算法的话可以看一下小甲鱼的数据结构然后去杭电hdu里面或者蓝桥杯里面做题。

慕雪6442864
TA贡献1812条经验 获得超5个赞
我明白你的想法,但是这样的算法是不行的,试想一下如果count是10,那你不是要写10个for循环来算10个数的和,并没有“写活”count让他自动就有10次for的方法(至少我没想到)。这道题应该是用搜索来做,个人感觉用深度搜素应该可以满足要求。
添加回答
举报
0/150
提交
取消