import Foundation
/// Generate all ways to write `n` as a sum of positive integers.
/// Example: n = 4 → [1+1+1+1], [1+1+2], [2+2], [1+3], [4]
///
/// - Parameters:
/// - n: The target number to partition.
/// - maxValue: The largest allowed value in the current step (prevents duplicates).
/// - current: The partial partition being built.
/// - result: The final list of all partitions.
func generatePartitions(
_ n: Int,
maxValue: Int,
current: inout [Int],
result: inout [[Int]]
) {
// Base case: if n reaches 0, we found a valid partition
if n == 0 {
result.append(current)
return
}
// Try all values from min(n, maxValue) down to 1
for value in stride(from: min(n, maxValue), through: 1, by: -1) {
// Choose this value
current.append(value)
// Recurse with reduced n and updated maxValue
generatePartitions(n - value, maxValue: value, current: ¤t, result: &result)
// Backtrack: remove last value and try next
current.removeLast()
}
}
/// Public function to get all partitions of a number.
func partitions(of n: Int) -> [[Int]] {
var result: [[Int]] = []
var current: [Int] = []
generatePartitions(n, maxValue: n, current: ¤t, result: &result)
return result
}
let n = 5
let all = partitions(of: n)
print("Partitions of \(n):")
for p in all {
print(p)
}
/*
run:
Partitions of 5:
[5]
[4, 1]
[3, 2]
[3, 1, 1]
[2, 2, 1]
[2, 1, 1, 1]
[1, 1, 1, 1, 1]
*/