Imports System
Imports System.Collections.Generic
Module IntegerPartitions
' Generate all ways to write a positive integer n
' as a sum of positive integers (integer partitions).
'
' Example for n = 5:
' [
' [ 5 ],
' [ 4, 1 ],
' [ 3, 2 ],
' [ 3, 1, 1 ],
' [ 2, 2, 1 ],
' [ 2, 1, 1, 1 ],
' [ 1, 1, 1, 1, 1 ]
' ]
' Function that returns all partitions of n
Function Partitions(n As Integer) As List(Of List(Of Integer))
Dim results As New List(Of List(Of Integer))()
Backtrack(n, n, New List(Of Integer)(), results)
Return results
End Function
' Backtracking helper function
Sub Backtrack(remaining As Integer,
maxValue As Integer,
current As List(Of Integer),
results As List(Of List(Of Integer)))
' If nothing remains, we found a valid partition
If remaining = 0 Then
results.Add(New List(Of Integer)(current))
Exit Sub
End If
' Try next numbers from maxValue down to 1
For nextValue As Integer = Math.Min(remaining, maxValue) To 1 Step -1
current.Add(nextValue) ' choose
Backtrack(remaining - nextValue, nextValue, current, results) ' explore
current.RemoveAt(current.Count - 1) ' un-choose (backtrack)
Next
End Sub
Sub Main()
Dim result = Partitions(5)
Console.WriteLine("[")
For i = 0 To result.Count - 1
Console.Write(" [ ")
For j = 0 To result(i).Count - 1
Console.Write(result(i)(j))
If j < result(i).Count - 1 Then Console.Write(", ")
Next
Console.Write(" ]")
If i < result.Count - 1 Then
Console.WriteLine(",")
Else
Console.WriteLine()
End If
Next
Console.WriteLine("]")
End Sub
End Module
' run:
'
' [
' [ 5 ],
' [ 4, 1 ],
' [ 3, 2 ],
' [ 3, 1, 1 ],
' [ 2, 2, 1 ],
' [ 2, 1, 1, 1 ],
' [ 1, 1, 1, 1, 1 ]
' ]
'