I want to find all the integer subsets that sum n via backtracking
For example for the integers:
1 2 3 4 5 6 7
and n = 7
I want to ouput
1 2 4
1 6
2 5
3 4
7
I think that I should pass the position in the integer array that I'm evaluating as argument, but I'm stuck writing the rest of the logic.
My code so far:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
/**
*
* @author talleres
*/
public class Main {
int sum (TreeSetts, int temp) {
int sum=0;
for (Integer i: ts){
sum +=i;
}
return sum+temp;
}
static HashSet> alternatives = new HashSet >();
static ArrayList> subsets = new ArrayList >();
static TreeSet getNextSubset (){
TreeSet alternative = new TreeSet();
if (!alternatives.contains(alternative)){
return alternative;
}
else return null; // BEWARE!!
}
static void findSubsets (ArrayList numbers, int amount, int index){
TreeSet subset = new TreeSet();
int temp = numbers.get(index); //initialize alternative
if (temp<=amount)
subset.add(temp);
if (temp==amount)
subsets.add(subset);
}
public static void main(String[] args) throws IOException {
// TODO code application logic here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("inset integers");
ArrayList numeros = new ArrayList();
String line=br.readLine();
while (!line.equals("")){
numeros.add (Integer.parseInt(line));
line = br.readLine();
}
Collections.sort(numeros);
System.out.println("insert the amount the subsets should sum");
line = br.readLine();
int amount = Integer.parseInt(line);
ArrayList accum = new ArrayList();
findSubsets(numeros, amount, 0);
}
}
解决方案
Here's some pseudo code for you to work with:
Set> subsets(Set remaining, int n) {
results = new HashSet>();
if (n == 0)
results.add(empty set);
for each i in remaining
newRemaining = remaining \ {i}
for each subresult in subsets(newRemaining, n - i)
results.add(subresult + {i})
return results
}
Should work for negative numbers as well. (uhm, actually will work. I implemented it and tested it before writing the pseudo code :-)