swift - 递归函数的大 O
问题描述
只是想知道,这个函数的大o是什么,假设参数的初始值如下:
numOfCourseIndex = 0
maximumScheduleCount = 1000
schedule = [[Section]]()
result = [[[Section]]]()
orderdGroupOfSections = n
.
func foo(numOfCourseIndex: Int, orderdGroupOfSections: [[[Section]]], maximumScheduleCount: Int) {
if (result.count >= maximumScheduleCount) {
return
}
for n in 0..<orderdGroupOfSections[numOfCourseIndex].count {
for o in 0..<orderdGroupOfSections[numOfCourseIndex][n].count {
for p in 0..<orderdGroupOfSections[numOfCourseIndex][n][o].sectionTime!.count {
for q in 0..<orderdGroupOfSections[numOfCourseIndex][n][o].sectionTime![p].day!.count {
///do something
}
}
}
if (numOfCourseIndex == orderdGroupOfSections.count - 1) {
result.append(schedule)
}
else {
foo(numOfCourseIndex: numOfCourseIndex + 1, orderdGroupOfSections: orderdGroupOfSections, maximumScheduleCount: maximumScheduleCount)
}
}
}
我说这是(n!)的Big-O作为最坏的情况,但我不确定。
解决方案
您可以做两件简单的事情来帮助您分析函数的复杂性。首先是简化输入并查看函数的行为方式。不要为大量课程或时间表或其他任何东西运行该功能,而是看看它只为一个课程做了什么。处理一门课程需要多少步骤?两个人多少?三?四?用结果做一个表格,然后看看一门课和两门课、二门课和三门课、三门课和四门课等的区别,你能看出一个规律吗?
您可以做的第二件事是将功能分解为多个部分并分别分析这些部分。你可能无法仅仅看到整个事物的复杂性,因为它是,嗯,复杂的。所以简化它......最内层循环的复杂性是什么?忽略最里面的第二个循环怎么样?两者的复杂性是什么?冲洗并重复。
推荐阅读
- c# - 从下拉列表中获取价值以在 asp.net 核心中建模
- bash - 如何使用 Bash 在文件目录上使用 ffmpeg 并让新文件保留相同的名称?
- flexbox - Flex 列上的 Vuetify 溢出导致整个页面溢出
- angular - 有没有办法从模板(使用 ng-ast)中获取 Angular AST?
- c - Fortran-C 互操作性基本示例
- html - 如何在这个“html 搜索栏”上添加多个表单和“操作”?
- java - 在 Spring Controller 中捕获无效参数
- rust - 如何为 UnixStream 和 TcpStream 创建多态类型
- postgresql - 不明确的列引用 - 它可以引用 PL/pgSQL 变量或表列?
- raspberry-pi - GPSD 没有看到完整的数据