Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to find all possible combinations of numbers from a list that equal to N in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

public class Program
{
	static void GetCombinationsEqualToN(List<int> arr, int N, List<int> combination) {
	   int sum = 0;

	   foreach (int num in combination) {
		   sum += num;
	   }

	   if (sum == N) {
			Console.WriteLine("sum(" + string.Join(",", combination.ToArray()) + ") = " + N);
	   }

	   if (sum >= N) {
			return;
	   }

	   for (int i = 0; i < arr.Count; i++) {
			 List<int> remaining = new List<int>();

			 for (int j = i + 1; j < arr.Count; j++) {
				 remaining.Add(arr[j]);
			 }

			 List<int> combination_next = new List<int>(combination);
			 combination_next.Add(arr[i]);

			 GetCombinationsEqualToN(remaining, N, combination_next);
	   }
	}

	public static void Main(string[] args)
	{
		List<int> list = new List<int>() {4, 6, 8, 2, 1, 10, 3, 5, 13};
		int N = 13;

		GetCombinationsEqualToN(list, N, new List<int>());
	}
}




/*
run:

sum(4,6,2,1) = 13
sum(4,6,3) = 13
sum(4,8,1) = 13
sum(4,1,3,5) = 13
sum(6,2,5) = 13
sum(8,2,3) = 13
sum(8,5) = 13
sum(2,1,10) = 13
sum(10,3) = 13
sum(13) = 13

*/

 



answered Oct 15, 2022 by avibootz
edited Oct 15, 2022 by avibootz
...