Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace SubsetSums_6
- {
- class SubsetSums6
- {
- private static int _sumOfNumbers;
- private static List<int> _numbers;
- private static bool _isResult;
- //Method that calculate the possible sums of elements
- private static void CalculateSubset(int startingPosition, List<int> numbersForSum)
- {
- if (numbersForSum.Sum() == _sumOfNumbers && numbersForSum.Count > 0)
- {
- Console.WriteLine("{0} = {1}", string.Join("+", numbersForSum), _sumOfNumbers);
- _isResult = true;
- }
- for (int number = startingPosition; number < _numbers.Count; number++)
- {
- numbersForSum.Add(_numbers[number]);
- //Calling recursivly the method CalculateSubset
- CalculateSubset(number + 1, numbersForSum);
- numbersForSum.RemoveAt(numbersForSum.Count - 1);
- }
- }
- private static void Main(string[] args)
- {
- _sumOfNumbers = int.Parse(Console.ReadLine());
- string input = Console.ReadLine();
- //Check if "input" is empty string or null
- if (!String.IsNullOrWhiteSpace(input))
- {
- //parse input to collection of integers and Distinct the collecion
- //so we will be sure that we don't have dublicated elements
- _numbers = input.Split().Select(int.Parse).Distinct().ToList();
- }
- //Creating new collection for our subset of numbers
- List<int> subset = new List<int>();
- CalculateSubset(0, subset);
- //Check if collection of numbers has a result
- //if not print the message
- if (!_isResult)
- {
- Console.WriteLine("No matching subsets.");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement