Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApplication6
- {
- class Program
- {
- static void Main(string[] args)
- {
- int n = int.Parse(Console.ReadLine());
- int[] numbers = Console.ReadLine().Split().Select(int.Parse).Distinct().ToArray();
- var subset = new List<int>();
- double combinations = Math.Pow(2, numbers.Length);
- bool isEqual = false;
- for (int i = 0; i < combinations; i++)//these are all of the possible combinations between numbers in the set, also called subset
- {
- int sum = 0; // here we save the value of the current sum
- for (int j = 0; j < numbers.Length; j++)// here we have all indexes if the numbers in the set
- {
- int mask = i & (1 << j); // Mask is extremely important. If the value of the mask is 001 we take only the first number, if the value is 101 we take the first and the third number etc.
- if (mask != 0)
- {
- sum += numbers[0 + j];
- subset.Add(numbers[0 + j]);
- }
- }
- if (sum == n)
- {
- Console.WriteLine(string.Join(" + ", subset) + " = " + sum);
- isEqual = true;
- }
- subset.Clear();
- }
- if (!isEqual)
- {
- Console.WriteLine("No matching subsets.");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment