public class ChildCollection {
public static Object isChildCollection(final int[] set, final int num) {
//1.定義參數tempSum和tempValue,後面存儲臨時的值
int tempSum,tempValue;
//2.定義參數result,返回的結果
boolean result = false;
//3.使用Math.pow(底數,幾次方)方法,循環2的冪次方次數,(覆蓋到了所有的選擇方案)
for (int i = 0; i < Math.pow(2, set.length); i++) {
//4.定義參數sum,存放集合的參數相加的結果
int sum = 0;
tempSum = i;
for (int j = 0; j < set.length; j++) {
//5.使用循環,判斷tempSum%2是否等於1(能否除盡),等於1,集合數值相加
if (tempSum % 2 == 1) {
sum += set[j];
}
tempSum /= 2;
}
//6.判斷sum的結果是否和num相等,如果相等,返回true
if (sum == num) {
tempValue = i;
System.out.println("存在子集合:" );
//7.循環輸出符合條件的子集合
for(int j = 0;j < set.length;j++){
if(tempValue % 2 == 1){
System.out.print(set[j]+ "," );
}
tempValue /= 2;
}
System.out.println("");
result = true;
}
}
return result;
}
public static void main (String[]args){
int set[] = {4, 14, 5, 9, 1, 17};
int sum = 10;
System.out.println(isChildCollection(set, sum));
}
}
給定一個整數,判斷給定集合中是否存在子集之和等於該整數?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.