-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
70 lines (62 loc) · 2.4 KB
/
Program.cs
File metadata and controls
70 lines (62 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using IndexSum.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IndexSum
{
class Program
{
static void Main(string[] args)
{
var numbers = new List<int>() { 1, 1, 2, 2, 4 };
PrintSumCombinations(numbers, 4);
}
public static void PrintSumCombinations(List<int> numbers, int n)
{
if (numbers == null || numbers.Count == 0) return;
numbers.Sort();
if (numbers.ElementAt(0) > n) return;
// initialize
var indexedNumbers = numbers.ToIndexedNumbers();
var candidate = new List<IndexedNumber>();
var sequences = new List<List<IndexedNumber>>();
// act
PermuteAndFind(ref indexedNumbers, ref candidate, ref sequences, n);
// print
Console.WriteLine(sequences.ToString(true));
}
public static void PermuteAndFind(ref List<IndexedNumber> numbers, ref List<IndexedNumber> candidate, ref List<List<IndexedNumber>> sequences, int n)
{
if (candidate.Sum() == n)
{
sequences.Add(new List<IndexedNumber>(candidate));
}
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i].Used) continue;
candidate.Add(numbers[i]);
numbers[i].Used = true;
PermuteAndFind(ref numbers, ref candidate, ref sequences, n);
candidate.Remove(numbers[i]);
numbers[i].Used = false;
}
}
public static void Combine(ref List<IndexedNumber> numbers, ref List<IndexedNumber> candidate, ref List<List<IndexedNumber>> sequences, int level, int start, int n)
{
for (int i = start; i < numbers.Count; i++)
{
if (candidate.Contains(numbers[i]) == false)
{
candidate[level] = numbers[i];
if (candidate.Sum() == n)
sequences.Add(new List<IndexedNumber>(candidate));
if (i < numbers.Count - 1)
Combine(ref numbers, ref candidate, ref sequences, level + 1, start + 1, n);
candidate[level] = new IndexedNumber() { Number = 0, Index = -1 };
}
}
}
}
}