在最大子数组问题中,涉及到暴力求解,那么,如何获取所有的子数组,写了个例子:
ListSubArray.swift
如下:
//1 2 3 12 13 23 123
let a = [1, 2, 3]
var subArray = [Any]()
for i in 1...a.count {
print("list \(i) length sub array")
print("")
for left in 0..<a.count {
let right = left + i
print("left is \(left) and right is \(right)")
if right < a.count+1 {
subArray.append(a[left..<right])
print(a[left..<right])
}
if right == a.count {
break
}
}
print("")
}
print("count is \(subArray.count) All subArray is \(subArray)")
Terminal
运行swift ListSubArray.swift
可得到:
list 1 length sub array
left is 0 and right is 1
[1]
left is 1 and right is 2
[2]
left is 2 and right is 3
[3]
list 2 length sub array
left is 0 and right is 2
[1, 2]
left is 1 and right is 3
[2, 3]
list 3 length sub array
left is 0 and right is 3
[1, 2, 3]
count is 6 All subArray is [ArraySlice([1]), ArraySlice([2]), ArraySlice([3]), ArraySlice([1, 2]), ArraySlice([2, 3]), ArraySlice([1, 2, 3])]