Code For NonGeek
Would you like to react to this message? Create an account in a few clicks or log in to continue.

print all subsets of an array whose sum equals one number

Go down

print all subsets of an array whose sum equals one number Empty print all subsets of an array whose sum equals one number

Post  yangwenzhou Fri Sep 23, 2011 12:03 pm

public class SubsetSum {

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();
}
}
}
}

yangwenzhou

Posts : 5
Join date : 2011-09-23

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum