从论坛里一哥们的回复中摘来的,反正我是受教了。
此算法有两种思路在里面。
1.遍历过程得到了所有子集的情况;
2.在1的基础之上得到和为10的子集。
纠正:上面1中所说有误,应是:遍历过程得到了所有和小于等于10的所有子集的情况。
补充:遍历所有子集的情况的代码如下
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();
}
}