Violations of general good practices
- Using
String.substringto extract single characters is odd. UseString.charAtinstead next time - Parsing single character strings using
Integer.parseIntis odd. UseString.charAt(index) - '0'instead allSubsetsshould be declared asSetinstead ofHashSet(use interface types instead of implementations)- Method names should be
camelCase - No need to write JavaDoc for private methods, simple comments are good enough, if needed at all
Strange way to collect integers
The way you collect integers in a String is strange in many ways:
- The program will not work for numbers > 9
- Appending digits to a string one by one, and then finally parsing them from the string one by one is strange.
You could use a Set instead. Sure, maybe it seems a bit strange and inefficient to clone the set in each recursive call, but I still think it would be better. It would also solve the problem you found, with the duplicate sequences in the results.
Probably there is an even better way, but I have no more time now.
Strange static and non-static variables
allSubsets is static, but input and target are not.
It would make more sense to either make all of these static, or none of them.
Not suggested implementation
I can't say I suggest this implementation, but it solves some issues with yours:
private void find(int[] input, int target, Set<Integer> ramp, int index) {
if (index > input.length - 1) {
if (getSum(ramp) == target) {
allSubsets.add(toString(ramp));
}
return;
}
find(input, target, updatedSet(ramp, input[index]), index + 1);
find(input, target, ramp, index + 1);
}
private Set<Integer> updatedSet(Set<Integer> ramp, int integer) {
Set<Integer> updated = new HashSet<Integer>();
updated.addAll(ramp);
updated.add(integer);
return updated;
}
private String toString(Set<Integer> ramp) {
StringBuilder builder = new StringBuilder();
for (Integer integer : ramp) {
builder.append(integer);
}
return builder.toString();
}
private static int getSum(Set<Integer> integers) {
int sum = 0;
for (Integer integer : integers) {
sum += integer;
}
return sum;
}