Advertisement
Guest User

Subset_Sum

a guest
Sep 17th, 2015
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. class Program
  8.  
  9. {
  10.  
  11. static int n;
  12. static int max;
  13. static int[] set;
  14. static List<int> subset;
  15. static byte[] binary;
  16. static int flag;
  17. static void Main()
  18. {
  19. max = int.Parse(Console.ReadLine());
  20. set = Console.ReadLine().Split(' ').Select(p => int.Parse(p)).Distinct().ToArray();
  21. n = set.Length;
  22. subset = new List<int>(n);
  23. binary = new byte[n];
  24. flag=0;
  25. int size = 2 << (n - 1);
  26. for(int i = 0; i < size; i++)
  27. {
  28. if(i!=0)
  29. Printsubset();
  30. BinaryIncrement();
  31. }
  32. if(flag==0)
  33. Console.WriteLine("No matching subsets");
  34. }
  35. static void BinaryIncrement()
  36. {
  37. for (int i = n - 1; i >= 0; i--)
  38. {
  39. if (binary[i] == 0)
  40. {
  41. binary[i] = 1;
  42. return;
  43. }
  44. binary[i] = 0;
  45. }
  46. }
  47. static void Printsubset()
  48. {
  49. subset.Clear();
  50. for(int i = n - 1; i >= 0; i--)
  51. {
  52. if (binary[i] == 1)
  53. subset.Add(set[n - 1 - i]);
  54. }
  55. if (subset.Sum() == max)
  56. {
  57. Console.WriteLine(String.Join(" + ", subset));
  58. flag = 1;
  59. }
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement