前言
学如逆水行舟,不进则退。Swift作为苹果官方推出的编程语言,今后也一定会成为主导地位,所以作为iOS开发君们,如果想长期从事iOS这份职业的,多多少少还是要懂点,今天呢,主要是给大家讲解的是Swift中求一个集合中子集。不知道当各位看到这里的时候是否脑海中已经有了答案呢。
问题:给定一个集合,求这个集合中有多少真子集?
方法一
func getSubSets<T>(set: Set<T>) -> Array<Set<T>> {
let count = 1 << set.count //set.count 不能超过64 否则将超过int最大数限制
let elements = Array(set)
var subsets = [Set<T>]()
for i in 0..<count {
var subset = Set<T>()
for j in 0..<elements.count {
if ((i >> j) & 1) == 1 {
subset.insert(elements[j])
}
}
subsets.append(subset)
}
return subsets
}
let testSet: Set = ["S","Y","Z"]
for subSet in getSubSets(set: testSet) {
print(subSet)
}
得出结果:
[]
["Y"]
["Z"]
["Y", "Z"]
["S"]
["Y", "S"]
["S", "Z"]
["Z", "Y", "S"]
方法二
func getSubSets<T>(_ set: Set<T>) -> Array<Set<T>> {
let elements = Array(set)
return getSubSetsDetail(elements, index: elements.count - 1, count: elements.count)
}
func getSubSetsDetail<T>(_ elements: Array<T>, index: Int, count: Int) -> Array<Set<T>> {
var subSets = Array<Set<T>>()
if index == 0 {
subSets.append(Set<T>())
var subset = Set<T>()
subset.insert(elements[0])
subSets.append(subset)
return subSets
}
subSets = getSubSetsDetail(elements, index: index - 1, count: count)
for subset in subSets {
var currentSubset = Set(subset)
currentSubset.insert(elements[index])
subSets.append(currentSubset)
}
return subSets
}
let testSet: Set = ["S","Y","Z"]
for subSet in getSubSets(testSet) {
print(subSet)
}
输出:
[]
["Y"]
["Z"]
["Y", "Z"]
["S"]
["S", "Y"]
["S", "Z"]
["S", "Y", "Z"]
总结
都说好记性都不如烂笔头,记录一些知识,防止遗忘。也可以温故而知新。
更多iOS知识可以关注主页哦!!!
网友评论