Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class SubsetSums
- {
- static void Main()
- {
- //Telerik Academy
- //You are given a list of N numbers. Write a program that counts all non-empty subsets from this list, which have sum of their elements exactly S.
- //Example: if you have a list with 4 elements: { 1, 2, 3, 4 } and you are searching the number of non-empty subsets which sum is 4, the answer will be 2. The subsets are: { 1, 3 } and { 4 }.
- long sumS = int.Parse(Console.ReadLine());
- byte numN = byte.Parse(Console.ReadLine());
- long[] numsArray = new long[numN];
- int subsCounter = 0;
- for (byte counter = 0; counter < numN; counter++)
- {
- long inputNumber = long.Parse(Console.ReadLine());
- numsArray[counter] = inputNumber;
- }
- int combinations = (1 << numN) - 1; // number of the combinations of the numbers which is 2^N-1 (excluding 0)
- for (int i = 1; i <= combinations; i++) // go through each combination
- {
- long subsetSum = 0;
- for (int j = 0; j < numN; j++) // checks each bit in i-th combination
- if (((i >> j) & 1) == 1) subsetSum += numsArray[j]; // and if bit is set includes corresponding number into the subsetSum
- if (subsetSum == sumS) subsCounter++; // each sum equal to sumS increases the subscounter
- }
- Console.WriteLine(subsCounter);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement