Integer[] datas = new Integer[]{1,2,3,4,5,6,7,8,9,10,11};//目標(biāo)數(shù)組Integer min = 6;//大于等于的值Integer max = 12;//小于等于的值Integer count = 3;//指定數(shù)量根據(jù)count如:3,3個(gè)數(shù)相加大于等于min小于等于max,2個(gè)數(shù)相加大于等于min小于等于max,1個(gè)數(shù)相加大于等于min小于等于max。如果count=2,2個(gè)........,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;
}輸出的【下標(biāo)】組合[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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊
這個(gè)是我老早以前,好像看一本<<妙趣橫生的算法>>里面學(xué)的。其實(shí)這個(gè)算法時(shí)間復(fù)雜度有點(diǎn)高。你要學(xué)算法的話可以看一下小甲魚的數(shù)據(jù)結(jié)構(gòu)然后去杭電hdu里面或者藍(lán)橋杯里面做題。

慕雪6442864
TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
我明白你的想法,但是這樣的算法是不行的,試想一下如果count是10,那你不是要寫10個(gè)for循環(huán)來算10個(gè)數(shù)的和,并沒有“寫活”count讓他自動(dòng)就有10次for的方法(至少我沒想到)。這道題應(yīng)該是用搜索來做,個(gè)人感覺用深度搜素應(yīng)該可以滿足要求。
添加回答
舉報(bào)
0/150
提交
取消