Given the following Input
10 4 3 5 5 7
Where
10 = Total Score
4 = 4 players
3 = Score by player 1
5 = Score by player 2
Here's the super naive solution that simply generates a power set on your input array and then iterates over each set to see if the sum satisfies the given total. I hacked it together with code already available on StackOverflow.
O(2n) in time and space. Gross.
You can use the idea of a Set
to store all indices into your arrays, then generate all permutations of those indices, and then use each set of indices to then go back into your array and get the values.
10
[3, 5, 5, 7]
import java.util.*;
import java.lang.*;
import java.io.*;
class SubsetSum
{
public static Set> powerSet(Set originalSet)
{
Set> sets = new HashSet>();
if (originalSet.isEmpty())
{
sets.add(new HashSet());
return sets;
}
List list = new ArrayList(originalSet);
T head = list.get(0);
Set rest = new HashSet(list.subList(1, list.size()));
for (Set set : powerSet(rest))
{
Set newSet = new HashSet();
newSet.add(head);
newSet.addAll(set);
sets.add(newSet);
sets.add(set);
}
return sets;
}
public static void main(String[] args)
{
Set mySet = new HashSet();
int[] arr={3, 5, 5, 7};
int target = 10;
int numVals = 4;
for(int i=0;i s : powerSet(mySet))
{
int sum = 0;
for (Integer e : s)
{
sum += arr[e];
}
if (sum == target)
{
String soln = "[ ";
for (Integer e : s)
{
soln += arr[e];
soln += " ";
}
soln += "]";
System.out.println(soln);
}
}
}
}
Solutions:
[ 5 5 ]
[ 3 7 ]
Live Demo
Once you understand this, perhaps you are ready to begin branch and bound or approximation approaches.