Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //* Write a program that reads three integer numbers N, K and S and an array
- //of N elements from the console. Find in the array a subset of K elements that
- //have sum S or indicate about its absence.
- using System;
- using System.Collections.Generic;
- class SubsetSumWithKElements
- {
- static void Main()
- {
- int n = int.Parse(Console.ReadLine());
- int countOfElements = int.Parse(Console.ReadLine());
- int sum = int.Parse(Console.ReadLine());
- int[] array = new int[n];
- List<int> subset = new List<int>();
- int max = (2 << array.Length - 1) - 1;
- int currentSum = 0;
- int answer = 0;
- int counter = 0;
- for (int k = 0; k < n; k++)
- {
- array[k] = int.Parse(Console.ReadLine());
- }
- for (int i = 1; i <= max; i++)
- {
- currentSum = 0;
- for (int p = 0; p < array.Length; p++)
- {
- if (((i >> p) & 1) == 1)
- {
- currentSum += array[p];
- subset.Add(array[p]);
- counter++;
- }
- }
- if (currentSum == sum && counter == countOfElements)
- {
- for (int p = 0; p < subset.Count; p++)
- {
- Console.Write(subset[p] + " ");
- }
- answer++;
- Console.WriteLine("= {0}", sum);
- }
- counter = 0;
- subset = new List<int>();
- }
- Console.WriteLine(answer + " combinations");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement