递归算法-求所有和为10的子集

本文详细介绍了使用Java实现的子集问题算法,包括生成所有子集和筛选特定和的子集。通过实例演示了如何遍历数组并利用递归或栈数据结构来解决子集问题,特别关注了如何优化算法以找到和为特定值的子集。
从论坛里一哥们的回复中摘来的,反正我是受教了。

import java.util.Stack;

public class SubsetCalc {

private int[] a = { 8, 5, 4, 3, 2, 1 };
private int sum = 10;
private Stack<Integer> stack = new Stack<Integer>();
private int stackSum = 0;

private void calc(int from, int to) {
if (stackSum == sum) {
for (Integer i : stack)
System.out.print(i + " ");
System.out.println();
return;
}

for (int i = from; i < to; i++) {
if (stackSum + a[i] <= sum) {
stackSum += stack.push(a[i]);
calc(i + 1, to);
stackSum -= stack.pop();
}
}
}

public void subsets() {
calc(0, a.length);
}

public static void main(String[] args) {
new SubsetCalc().subsets();
}
}

此算法有两种思路在里面。
1.遍历过程得到了所有子集的情况;
2.在1的基础之上得到和为10的子集。

纠正:上面1中所说有误,应是:遍历过程得到了所有和小于等于10的所有子集的情况。
补充:遍历所有子集的情况的代码如下

public class RecursionTest {

private int[] a={8,5,4,3,2,1};
private Stack<Integer> stack=new Stack<Integer>();

private void calc(int from, int to)
{
for(int i=from;i<to;i++)
{
stack.push(a[i]);
calc(i+1,to);
stack.pop();
}
for(Integer i:stack)
{
System.out.print(i+" ");
}
System.out.println();
}
public void subsets()
{
calc(0,a.length);
}
public static void main(String[] args) {
new RecursionTest().subsets();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值