java - 置换 DFS 解决方案的实时复杂度
问题描述
https://leetcode.com/problems/permutations/ 常见的解决方案是 DFS 递归
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0)
return res;
DFS(0, nums, res);
return res;
}
private void DFS(int index, int[] nums, List<List<Integer>> res) {
if (index == nums.length) {
**//covert nums to list and add to res** o(n)
return;
}
for (int i = index; i < nums.length; i++) {
swap(nums, index, i);
DFS(index + 1, nums, res);
swap(nums, index, i);
}
}
private void swap(int[] nums, int left, int right) {
int tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
}
}
从数学中我们可以看到总共有 n! 不同的排列,很多人说 o(n!) 是时间复杂度
但是从代码中我们可以看到递归是 T(n) = O(n)(for add to permutation) + T(n-1) + T(n-2) + ... + T(2) + T( 1)而且我认为 O(n!) 忽略 O(n) 以增加排列我不知道如何从这种重复中概括出一个大 O,任何人都可以帮忙。
非常感谢
解决方案
推荐阅读
- routes - 是否可以将所有请求映射到某个路径下的路由,即“/api/**”到pcf中的不同应用程序?
- php - 通过PHP避免Mysql中的重复
- javascript - 为什么 toString() 是一个不需要对象的方法?
- python - 将多个经过训练的 CNN 模型权重文件合并到一个文件中
- ios - 如何确定 UILabel 的点击来自何处?
- unity3d - 递归生成器实例化太多游戏对象
- magento - 如何使用专用服务器上的 cPanel 在 Magento 2.3 上安装 Venia PWA 主题?
- ionic3 - Ionic 3 存储保存一页但不保存下一页
- javascript - 如何使用伪元素::before 在 li 上制作 onclick 事件
- java - 如何重复不成功的 Realm 交易?