尋找和爲定值的N個數
題目:
輸入兩個整數n和sum,要求從數列1, 2, 3, ...,n中隨意取出幾個數,使得它們的和等於sum,請將其中所有可能的組合列出來。
思路:
上述問題是典型的揹包問題的應用,即先找出n個數的所有組合,再在這些組合中尋找組合數相加之和等於sum的組合,並依次輸出這些組合中的數。
實現:
public class ManySumN {
public static void main(String[] args) {
new ManySumN().printManySumN(5, 4);
}
public String[] getAllGroup(int n) {
intlen = (int) Math.pow(2, n);
String[] result = new String[len];
if(n == 1) {
result[0]= "0";
result[1]= "1";
return result;
}
String[] temp = getAllGroup(n - 1);
for(int i = 0; i < temp.length; i++) {
result[i]= "0" + temp[i];
result[len- 1 - i] = "1" + temp[i];
}
return result;
}
public void printManySumN(int n, int sum){
String[] allGroup = getAllGroup(n);
for(int i = 0; i < allGroup.length; i++) {
char[]temp = allGroup[i].toCharArray();
inttempSum = 0;
for(int j = 0; j < temp.length; j++) {
if(temp[j]=='1'){
tempSum+=(j+1);
}
}
if(tempSum== sum){
for(int j=0;j<temp.length;j++){
if(temp[j]=='1'){
System.out.print((j+1)+"");
}
}
System.out.println();
}
}
}
}