Combination Sum - c# solution


  • 0
    J
    class Program
        {
            static void Main(string[] args)
            {
                List<List<int>> results = new List<List<int>>();
                List<int> result = new List<int>();
                List<int> input = new List<int>() {2,2, 4, 5, 6, 8 };
                input.Sort();
                CombinationalSum(results, result, input, 12, 0);
    
                foreach(var result1 in results)
                {
                    foreach(var id in result1)
                    {
                        Console.Write(id + ",");
                    }
                    Console.WriteLine();
                }
                Console.ReadLine();
            }
            static void CombinationalSum(List<List<int>> results, List<int> result, List<int> input, int target, int index)
            {
                
                int sum = 0;
                foreach(int x in result)
                {
                    sum += x;
                }
    
                if(sum == target)
                {
                    results.Add(new List<int>(result));
                    return;
                }
    
                if(sum < target)
                {
                    for(int i = index; i< input.Count(); i++)
                    {
                        if(index != i && input[i] == input[i-1])
                        {
                            continue;
                        }
    
                        result.Add(input[i]);
                        CombinationalSum(results, result, input, target, i + 1);
                        result.RemoveAt(result.Count() - 1);
                    }
                }
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.