台哥算法练习 - 寻找和为某值的子集

这是09年日全食那段时间,有一次班级群里,一个同学提出来的问题,当时随手写了这个算法。

题目:从一个数字的集合里,找出所有的子集,这些子集的和等于15

直接贴出代码咯:

package suanfa;

/**
 * 集合中寻找和为某值的子集
 * 
 * @author 台哥编程课堂
 * https://blog.csdn.net/chaohi
 * 
 * 这里是定义了个数组集合,从中查找和为15的集合。递归法和贪心法的结合,不断迭代。。
 */
public class Jihe {
	int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
	int target = 15;

	/**
	 * 
	 * @param index
	 * @param he
	 * @param array
	 * @param tai
	 */
	public void action(int index, int he, int[] array, String str) {
		String xyz = "";
		
		for (int i = index; i < array.length; i++) {
			int j = array[i];
			xyz = str + " + " + j;
			if (j < he) {
				action(i + 1, he - j, array, xyz);
			}
			if (j == he) {
				System.out.println(xyz.substring(3) + " =" + this.target);
				str = "";
			}
		}
	}

	public static void main(String[] args) {
		Jihe jihe = new Jihe();
		jihe.action(0, jihe.target, jihe.array, "");
	}
}

运行,打印结果如下:

1 + 2 + 3 + 4 + 5 =15
1 + 2 + 3 + 9 =15
1 + 2 + 4 + 8 =15
1 + 2 + 5 + 7 =15
1 + 3 + 4 + 7 =15
1 + 3 + 5 + 6 =15
1 + 5 + 9 =15
1 + 6 + 8 =15
2 + 3 + 4 + 6 =15
2 + 4 + 9 =15
2 + 5 + 8 =15
2 + 6 + 7 =15
3 + 4 + 8 =15
3 + 5 + 7 =15
4 + 5 + 6 =15
6 + 9 =15
7 + 8 =15
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值