美文网首页无法删除的专题
获取数组中所有的子数组-Swift3.0 实现

获取数组中所有的子数组-Swift3.0 实现

作者: Jiubao | 来源:发表于2016-07-27 17:01 被阅读75次

在最大子数组问题中,涉及到暴力求解,那么,如何获取所有的子数组,写了个例子:
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])]

相关文章

网友评论

  • sven7:有没有OC版本啊亲

本文标题:获取数组中所有的子数组-Swift3.0 实现

本文链接:https://www.haomeiwen.com/subject/jdiojttx.html