Skip to content

Instantly share code, notes, and snippets.

@svaza
Created January 12, 2022 03:48
Show Gist options
  • Select an option

  • Save svaza/a838e756f6f8876d4514b6dc471765f7 to your computer and use it in GitHub Desktop.

Select an option

Save svaza/a838e756f6f8876d4514b6dc471765f7 to your computer and use it in GitHub Desktop.
combination sum
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
public class Solution
{
public class ListBak
{
public List<int> List { get; set; }
public ListBak(List<int> List)
{
this.List = List;
}
public override int GetHashCode()
{
var hash = 0;
foreach (var item in List)
{
hash += HashCode.Combine(item);
}
return hash;
}
public override bool Equals(object obj)
{
return GetHashCode() == obj.GetHashCode();
}
}
public class ObjectEqualityComparer : IEqualityComparer<ListBak>
{
public bool Equals([AllowNull] ListBak x, [AllowNull] ListBak y)
{
return x.Equals(y);
}
public int GetHashCode([DisallowNull] ListBak obj)
{
return obj.GetHashCode();
}
}
private HashSet<ListBak> sumList = new HashSet<ListBak>(new ObjectEqualityComparer());
private int target;
private int[] candidates;
public IList<IList<int>> CombinationSum(int[] candidates, int target)
{
Array.Sort(candidates);
this.candidates = candidates;
this.target = target;
this.SearchCandidates(0, new Stack<int>());
return sumList.Select(e=> e.List).Cast<IList<int>>().ToList();
}
private void SearchCandidates(int sum, Stack<int> runningSum)
{
if (sum == target)
{
var lst = new ListBak(new List<int>(runningSum));
lst.List.Sort();
sumList.Add(lst);
return;
}
else if(sum > target)
{
return;
}
else
{
for (int i = 0; i < candidates.Length; i++)
{
runningSum.Push(candidates[i]);
sum += candidates[i];
this.SearchCandidates(sum, runningSum);
sum -= candidates[i];
runningSum.Pop();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment