How to find the unique combination k sum that corresponds to k sum using C#?

CsharpServer Side ProgrammingProgramming

Create an output list to store the valid sequences, create a current list that will store the current sequence found in the path of the recursion tree. A backtrack function that will go into the recursion until the target is achieved, otherwise, it should backtrack to the previous phase as target becomes less than 0. At any point in time, if target becomes 0 then add the candidate array to the result as the values in the candidate array must be sum up to the given target.

If those are not the cases then, one by one add the elements in the candidate array and recursively move forward.

Say, the number is 5 and k is 2 so we need to form the combination of numbers in the size 2 that forms 5. The output will be “1,4”,”2,3”.

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace ConsoleApplication{
   public class BackTracking{
      public void UniqueCombinationSumOfExactKNumbers(int n, int k){
         int[] array = new int[n];
         for (int i = 1; i < n; i++){
            array[i] = i;
         }
         List<int> currentList = new List<int>();
         List<List<int>> output = new List<List<int>>();
         UniqueCombinationSumOfExactKNumbers(array, n, k, 0, 0, currentList, output);
         foreach (var item in output){
            StringBuilder s = new StringBuilder();
            foreach (var item1 in item){
               s.Append(item1.ToString());
            }
            Console.WriteLine(s);
            s = null;
         }
      }
      private void UniqueCombinationSumOfExactKNumbers(int[] array, int target, int countOfNumbers, int sum, int index, List<int> currentList, List<List<int>> output){
         if (sum == target){
            if (currentList.Count == countOfNumbers){
               List<int> newList = new List<int>();
               newList.AddRange(currentList);
               output.Add(newList);
               return;
            }
         }
         else if (sum > target){
            return;
         }
         else if (currentList.Count == countOfNumbers && sum != target){
            return;
         }
         else{
            for (int i = index; i < array.Length; i++){
               currentList.Add(array[i]);
               UniqueCombinationSumOfExactKNumbers(array, target, countOfNumbers, sum + array[i], i + 1, currentList, output);
               currentList.Remove(array[i]);
            }
         }
      }
   }
   class Program{
      static void Main(string[] args){
         BackTracking b = new BackTracking();
         b.UniqueCombinationSumOfExactKNumbers(5, 2);
      }
   }
}

Output

14
23
raja
Published on 27-Aug-2021 13:25:19
Advertisements