Advertisement
Guest User

Untitled

a guest
Jul 16th, 2015
487
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.98 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace SubsetSums_6
  6. {
  7.     class SubsetSums6
  8.     {      
  9.         private static int _sumOfNumbers;
  10.         private static List<int> _numbers;
  11.         private static bool _isResult;
  12.  
  13.         //Method that calculate the possible sums of elements
  14.         private static void CalculateSubset(int startingPosition, List<int> numbersForSum)
  15.         {
  16.             if (numbersForSum.Sum() == _sumOfNumbers && numbersForSum.Count > 0)
  17.             {
  18.                 Console.WriteLine("{0} = {1}", string.Join("+", numbersForSum), _sumOfNumbers);
  19.                 _isResult = true;
  20.             }
  21.             for (int number = startingPosition; number < _numbers.Count; number++)
  22.             {
  23.                 numbersForSum.Add(_numbers[number]);
  24.  
  25.                 //Calling recursivly the method CalculateSubset                              
  26.                 CalculateSubset(number + 1, numbersForSum);
  27.                 numbersForSum.RemoveAt(numbersForSum.Count - 1);
  28.             }
  29.         }
  30.         private static void Main(string[] args)
  31.         {
  32.             _sumOfNumbers = int.Parse(Console.ReadLine());
  33.             string input = Console.ReadLine();
  34.  
  35.             //Check if "input" is empty string or null
  36.             if (!String.IsNullOrWhiteSpace(input))
  37.             {
  38.                 //parse input to collection of integers and Distinct the collecion
  39.                 //so we will be sure that we don't have dublicated elements
  40.                 _numbers = input.Split().Select(int.Parse).Distinct().ToList();
  41.             }
  42.  
  43.             //Creating new collection for our subset of numbers
  44.             List<int> subset = new List<int>();
  45.             CalculateSubset(0, subset);
  46.  
  47.             //Check if collection of numbers has a result
  48.             //if not print the message
  49.             if (!_isResult)
  50.             {
  51.                 Console.WriteLine("No matching subsets.");
  52.             }
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement