print all subsets of an array whose sum equals one number
Page 1 of 1
print all subsets of an array whose sum equals one number
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();
}
}
}
}
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
Similar topics
» Given a magic number sum, to find if there are two numbers whose sum equals to the number
» An array of integers, all appear twice except one, find this number.
» Find the number of inversions in an array
» In an array there is one element which repeats more than n/2 times...find the number in 0(n) time and 0(1) space
» Given a sorted array find all possible |ai - aj| where ai,aj belongs to Array A. n^2 is obvious. Find a solution in O(N).
» An array of integers, all appear twice except one, find this number.
» Find the number of inversions in an array
» In an array there is one element which repeats more than n/2 times...find the number in 0(n) time and 0(1) space
» Given a sorted array find all possible |ai - aj| where ai,aj belongs to Array A. n^2 is obvious. Find a solution in O(N).
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|