Advertisement
Guest User

Untitled

a guest
Sep 16th, 2015
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. class SubSetSums
  7. {
  8. static void Main()
  9. {
  10. int num = int.Parse(Console.ReadLine());
  11. int[] n = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
  12. int[] seq = n.Distinct().ToArray();
  13.  
  14. double combinations = Math.Pow(2, seq.Length);
  15.  
  16. List<int> intList = new List<int>();
  17. int count = 0;
  18.  
  19. for (int i = 1; i < combinations; i++)
  20. {
  21. int sum = 0;
  22. CheckCombination(i, seq, ref intList);
  23. sum = intList.Sum();
  24.  
  25. if ( sum == num )
  26. {
  27. Console.WriteLine("{0} = {1}",
  28. string.Join(" + ", intList.Select(x => x.ToString()).ToArray()),
  29. intList.Sum()
  30. );
  31. count++;
  32. }
  33.  
  34. intList = new List<int>();
  35. }
  36. if (count == 0)
  37. {
  38. Console.WriteLine("No matching subsets.");
  39. }
  40. }
  41.  
  42. private static void CheckCombination(int mask, int[] intArr, ref List<int> intList)
  43. {
  44. int sumOfComb = 0;
  45. for (int i = 0; i < intArr.Length; i++)
  46. {
  47. if (mask % 2 != 0)
  48. {
  49. sumOfComb += intArr[i];
  50. intList.Add(intArr[i]);
  51. //Console.Write(intArr[i]);
  52. }
  53. mask >>= 1;
  54.  
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement