Created
May 10, 2015 11:25
-
-
Save aanguelov/91c860f0f7005445371d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace SortedSubsetSums | |
{ | |
class SortedSubsetSums | |
{ | |
static void Main(string[] args) | |
{ | |
int n = int.Parse(Console.ReadLine()); | |
string[] input = Console.ReadLine().Split(' '); | |
int[] arr = new int[input.Length]; | |
for (int i = 0; i < arr.Length; i++) | |
{ | |
arr[i] = int.Parse(input[i]); | |
} | |
arr = arr.Distinct().ToArray(); | |
Array.Sort(arr); | |
List<int> tempSubset = new List<int>(); | |
List<List<int>> matchedSubsets = new List<List<int>>(); | |
int combinations = 1 << arr.Length; | |
bool noSubsets = false; | |
for (int i = 1; i < combinations; i++) | |
{ | |
for (int j = 0; j < arr.Length; j++) | |
{ | |
int mask = i & (1 << j); | |
if (mask != 0) | |
{ | |
tempSubset.Insert(0, arr[arr.Length - 1 - j]); | |
} | |
} | |
if (tempSubset.Sum() == n) | |
{ | |
matchedSubsets.Insert(0, new List<int>(tempSubset)); | |
noSubsets = true; | |
} | |
tempSubset = new List<int>(); | |
} | |
var ordered = matchedSubsets.OrderBy(x => x.Count); | |
foreach (var item in ordered) | |
{ | |
Console.WriteLine("{0} = {1}",string.Join(" + ",item),n); | |
} | |
if (!noSubsets) | |
{ | |
Console.WriteLine("No matching subsets."); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment