Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    Combinations that add up to a target

    MediumAbout 25 minFull AccessLearn it: Permutations and Combination Sum: undo and pruning

    The task

    A ticket machine sells passes of a few fixed durations, and a traveller wants to see every way to cover an exact number of days.

    Complete CombinationSum(int[] candidates, int target). The candidates are distinct, positive and in any order, and each may be used any number of times. Return every combination of candidates whose sum is target (0 or more), each combination once. The combinations may come in any order, and so may the values inside one (the tests sort before comparing). A target of 0 gives one empty combination.

    Signature

    public static List<List<int>> CombinationSum(int[] candidates, int target)

    Examples

    • [3, 4, 5], 9 → [[3, 3, 3], [4, 5]]. 3 + 3 + 3 and 4 + 5; 5 + 4 is the same combination.
    • [4, 6], 5 → []. No mix of 4s and 6s makes 5.

    Limits: Up to 10 candidates of up to 100, and a target of up to 60.

    The tests check: a target too small, a target of 0, candidates in any order, a candidate used many times, no combination at all, combinations that must not repeat, and targets of 30 and 60 in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public static class Solution
      {
          // Every combination of reusable candidates whose sum is target, each combination once.
          public static List<List<int>> CombinationSum(int[] candidates, int target)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.