using System.Collections.Generic;
static bool CanSumHelper(int[] candidates, int target)
Dictionary<int, bool> memo = new Dictionary<int, bool>();
bool CanSumHelper(int currentTarget)
if (memo.ContainsKey(currentTarget))
return memo[currentTarget];
foreach (int candidate in candidates)
int newTarget = currentTarget - candidate;
if (CanSumHelper(newTarget))
memo[currentTarget] = true;
memo[currentTarget] = false;
return CanSumHelper(target);
public static void check(int[] candidates, int target, bool expected)
bool result = CanSumHelper(candidates, target);
Console.WriteLine(candidates + (expected ? " HAS " : " DOES NOT HAVE ") + target + " = " + (result == expected));
public static void Main()
check(new int[] { 2, 7, 6, 3 }, 18, true);
check(new int[] { 2, 1, 7, 6, 3}, 18, true);
check(new int[] { 2, 7, 6, 1, 3 }, 18, true);
check(new int[] { 2, 7, 6, 3, 1 }, 18, true);
check(new int[] { 1, 2, 7, 6, 3 }, 18, true);
check(new int[] { 2, 7, 8, 3 }, 9, true);
check(new int[] { 2, 7, 8, 3 }, 10, true);
check(new int[] { 2, 7, 8, 3 }, 5, true);
check(new int[] { 2, 7, 8, 3 }, 15, true);
check(new int[] { 2, 7, 8, 3 }, 11, true);
check(new int[] { 2, 7, 8, 3 }, 1, false);
check(new int[] { 2, 7, 8, 3 }, 4, false);
check(new int[] { 2, 7, 8, 3 }, 6, false);
check(new int[] { 2, 7, 8, 3 }, 14, false);
check(new int[] { 2, 7, 8, 3 }, 16, false);
check(new int[] { 2, 7, 8, 3 }, 19, false);