子集和数问题
[问题描述]
已知n个正数:wi, 1<=i<=n, 和M。要求找出{wi }的所有子集使得子集内元素之和等于M。例如:
n=4, (w1,w2,w3,w4)=(11,13,24,7),M=31
则满足要求的子集是(11,13,7)和(24,7)。
/*子集和数问题:已知n个正数:wi, 1<=i<=n, 和M。 要求找出{wi }的所有子集使得子集内元素之和等于M。例如: n=4, (w1,w2,w3,w4)=(11,13,24,7),M=31 则满足要求的子集是(11,13,7)和(24,7)。 思路: 子集和数问题解的一种表示方法 解由n-元组(x1, x2, …, xn)表示; 显式约束条件xi∈{0,1} ,1≤i≤n,如果没有选择Wi,则xi=0; 如果选择了Wi,则xi=1。于是上面的解可以表示为(1,1,0,1)和(0,0,1,1); 隐式约束条件(xi× wi)的和数为M */ public class sonNum { //定义一个数组表示集合 static int[] num = {11,13,24,7}; //sum用来做加法,比较判断是否等于m static int sum = 0; //用来表示最终的解{0,1,1,1}形式 static int[] result = new int[num.length]; //给定的m static int m = 31; //回溯方法 static public void backTrack(int count){ //如果count等于集合的长度则代表已经运行结束 if(count == result.length){ return; } else{ //1的情况代表选择将该数加进sum里,0的情况就是不要这个数 for (int i = 0; i <= 1 ; i++) { sum += i*num[count]; //result用来记录是否选择该数 选择则置1,不选择则置0 result[count] = i ; //如果运行到sum等于m的时候,则代表找到了一组解 //将这组解打印输出 if(sum == m){ for (int j = 0; j < result.length; j++) { //判断当前数的状态是否为选中状态 是则将该数打印出来 if(result[j] == 1){ System.out.print(num[j]+"\t"); } } System.out.println(); } //如果当前sum小于m,则进行下一个数的判断 if(sum < m){ backTrack(count+1); } //回溯 sum -= i*num[count]; } } } public static void main(String[] args) { backTrack(0); } }
posted on 2017-12-21 17:28 Marvellous 阅读(3164) 评论(0) 编辑 收藏 举报