您的位置:首页 > 编程语言 > Java开发

算法笔记_041:寻找和为定值的多个数(Java)

2017-02-20 21:15 375 查看

1 问题描述

输入两个整数n和sum,要求从数列1,2,3,...,n中随意取出几个数,使得它们的和等于sum,请将其中所有可能的组合列出来。

2 解决方案

上述问题是典型的背包问题的应用,即先找出n个数的所有组合,再在这些组合中寻找组合数相加之和等于sum的组合,并依次输出这些组合中的数。

具体代码如下:

package com.liuzhen.array_2;

public class ManySumN {
/*
* 函数功能:以字符串形式返回1~n个数的所有子集,其中0代表不包含其中数字i,1代表 包含其中数字i
* 此段代码是运用反射格雷码的思想,具体解释详见:算法笔记_019:背包问题(Java)

*/
public String[] getAllGroup(int n){
int len = (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;
}
/*
* 参数n:代表有1~n的n个不同整数
* 函数功能:打印出1~n中所有随机组合的几个数,其相加的和等于sum
*/
public void printManySumN(int n,int sum){
System.out.println("1~"+n+"个数中,相加之和等于"+sum+"的所有组合数为:");
String[] allGroup = getAllGroup(n);
for(int i = 0;i < allGroup.length;i++){
char[] temp = allGroup[i].toCharArray();
int tempSum = 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();
}
}
}

public static void main(String[] args){
ManySumN test = new ManySumN();
test.printManySumN(10, 16);
}
}


[b]运行结果:[/b]

1~10个数中,相加之和等于16的所有组合数为:
7 9
6 10
4 5 7
3 4 9
3 5 8
3 6 7
2 3 5 6
2 3 4 7
2 4 10
2 5 9
2 6 8
1 2 6 7
1 2 5 8
1 2 4 9
1 2 3 4 6
1 2 3 10
1 3 5 7
1 3 4 8
1 4 5 6
1 5 10
1 6 9
1 7 8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: