利用https://stackoverflow.com/a/20049365/1187415的思路,可以这样
在 Swift 中完成
// Append all elements of a2 to each element of a1
func combihelper(a1 : [[Int]], a2 : [Int]) -> [[Int]] {
var result = [[Int]]()
for elem1 in a1 {
for elem2 in a2 {
result.append(elem1 + [elem2])
}
}
return result
}
func combinations(array : [[Int]]) -> [[Int]] {
// Start with the "empty combination" , then successively
// add combinations with each row of array:
var result : [[Int]] = [[]]
for row in array {
result = combihelper(result, row)
}
return result
}
最后一个函数可以写得更快捷
func combinations(array : [[Int]]) -> [[Int]] {
return reduce(array, [[]]) { combihelper($0, $1) }
}
例子:
let myArray = [[1],
[2,3,4],
[5,6],
]
let result = combinations(myArray)
println(result)
// [[1, 2, 5], [1, 2, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6]]
(如果您的输入不限于整数,您可以将上面的Int替换为Any
功能。)
Swift 3 的更新并作为通用函数,因此它可以
与任何元素类型一起使用:
func combihelper<T>(a1 : [[T]], a2 : [T]) -> [[T]] {
var result = [[T]]()
for elem1 in a1 {
for elem2 in a2 {
result.append(elem1 + [elem2])
}
}
return result
}
func combinations<T>(of array: [[T]]) -> [[T]] {
return array.reduce([[]]) { combihelper(a1: $0, a2: $1) }
}
let myArray = [[1],
[2,3,4],
[5,6],
]
let result = combinations(of: myArray)
print(result) // [[1, 2, 5], [1, 2, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6]]