Skip to content

Instantly share code, notes, and snippets.

@SecretDeveloper
Last active September 25, 2015 07:28
Show Gist options
  • Save SecretDeveloper/885645 to your computer and use it in GitHub Desktop.
Save SecretDeveloper/885645 to your computer and use it in GitHub Desktop.
.Net solution to the subset sum problem.
public class SubSetSolver
{
// Define other methods and classes here
public void Solve(string input)
{
List<int> seq = input.Split(',').Select(x => int.Parse(x)).ToList();
seq.Sort();
List<List<int>> combinations = new List<List<int>>(seq.Count *2);
combinations.Add(new List<int>());
foreach (int i in seq)
{
List<List<int>> tmp = new List<List<int>>(seq.Count * seq.Count);
//Console.WriteLine(string.Format("{0}",i));
foreach (List<int> comb in combinations)
{
// Here we check if the current set sum + i is greater than 0
// If it is we skip adding this set to our collection as it is beyond our target.
// This only works on a SORTED input. ie any future "i" will >= current "i".
if (comb.Sum() + i <= 0)
{
var tmpComb = new List<int>(comb);
tmpComb.Add(i); // add the current item to the current combination
tmp.Add(tmpComb); // Add the new combination to our temp list
}
}
combinations.AddRange(tmp);
}
foreach (List<int> c in combinations.Where(x => x.Count != 0 && x.Sum() == 0))
{
Console.WriteLine(string.Format("[{0}]", string.Join(", ", c.Select(x=>x.ToString()).ToArray())));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment