Merge pull request #2058 from juguagua/leetcode-add-complexity-analysis-backtracking

添加复杂度分析:回溯部分
This commit is contained in:
程序员Carl
2023-05-09 09:57:57 +08:00
committed by GitHub
14 changed files with 35 additions and 0 deletions

View File

@ -183,6 +183,8 @@ public:
}
};
```
* 时间复杂度: O(3^m * 4^n),其中 m 是对应四个字母的数字个数n 是对应三个字母的数字个数
* 空间复杂度: O(3^m * 4^n)
一些写法,是把回溯的过程放在递归函数里了,例如如下代码,我可以写成这样:(注意注释中不一样的地方)

View File

@ -214,6 +214,8 @@ public:
}
};
```
* 时间复杂度: O(n * 2^n),注意这只是复杂度的上界,因为剪枝的存在,真实的时间复杂度远小于此
* 空间复杂度: O(target)
# 总结

View File

@ -214,6 +214,8 @@ public:
};
```
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n)
## 补充

View File

@ -136,6 +136,8 @@ public:
}
};
```
* 时间复杂度: O(n!)
* 空间复杂度: O(n)
## 总结

View File

@ -99,6 +99,8 @@ public:
};
```
* 时间复杂度: O(n)
* 空间复杂度: O(n)
## 拓展

View File

@ -208,6 +208,9 @@ public:
}
};
```
* 时间复杂度: O(n!)
* 空间复杂度: O(n)
可以看出,除了验证棋盘合法性的代码,省下来部分就是按照回溯法模板来的。

View File

@ -218,6 +218,10 @@ public:
}
};
```
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n)
还记得我们在[关于回溯算法,你该了解这些!](https://programmercarl.com/回溯算法理论基础.html)中给出的回溯法模板么?

View File

@ -130,6 +130,10 @@ public:
}
};
```
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n)
# 总结

View File

@ -149,6 +149,8 @@ public:
};
```
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n)
在注释中,可以发现可以不写终止条件,因为本来我们就要遍历整棵树。

View File

@ -83,6 +83,9 @@ public:
}
};
```
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n)
使用set去重的版本。
```CPP

View File

@ -244,6 +244,8 @@ public:
};
```
* 时间复杂度: O(3^4)IP地址最多包含4个数字每个数字最多有3种可能的分割方式则搜索树的最大深度为4每个节点最多有3个子节点。
* 空间复杂度: O(n)
# 总结

View File

@ -209,6 +209,9 @@ public:
}
};
```
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n^2)
# 优化
上面的代码还存在一定的优化空间, 在于如何更高效的计算一个子字符串是否是回文字串。上述代码```isPalindrome```函数运用双指针的方法来判定对于一个字符串```s```, 给定起始下标和终止下标, 截取出的子字符串是否是回文字串。但是其中有一定的重复计算存在:

View File

@ -235,6 +235,8 @@ public:
}
};
```
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n)
# 总结

View File

@ -139,6 +139,8 @@ public:
}
};
```
* 时间复杂度: O(n * 2^n)
* 空间复杂度: O(n)
## 优化