12
返回列表 发新帖
楼主: 超人96825
跳转到指定楼层
上一主题 下一主题
收起左侧

[树/链表/图] 加米,求帮忙看篮子王LC46的IndexOutOfBoundException

🔗
 楼主| 超人96825 2019-12-9 01:29:22 | 只看该作者
全局:
菊二二二二 发表于 2019-12-8 03:47
同上,等于说把倒数第二个删掉了
谢谢,现在明白了!
回复

使用道具 举报

🔗
 楼主| 超人96825 2019-12-9 01:29:33 | 只看该作者
全局:
dreamy 发表于 2019-12-7 08:40
13 和 14 换一下? 要删的是加进去的那个最后的元素
谢谢,现在明白了!
回复

使用道具 举报

🔗
 楼主| 超人96825 2019-12-9 01:29:44 | 只看该作者
全局:
337845818 发表于 2019-12-8 01:31
clist 为空时, 考虑一下
谢谢,现在明白了!
回复

使用道具 举报

🔗
 楼主| 超人96825 2019-12-9 01:45:17 | 只看该作者
全局:
WarriorZ 发表于 2019-12-8 05:34
求permutation还有比N!更优的解法吗?能给个链接看一下吗?

hi,我的理解来看,这个解法时间复杂度不是n!,而是O(n * n!)。

leetcode里给出的solution提供了这个解法:

  1. class Solution {
  2.   public void backtrack(int n,
  3.                         ArrayList<Integer> nums,
  4.                         List<List<Integer>> output,
  5.                         int first) {
  6.     // if all integers are used up
  7.     if (first == n)
  8.       output.add(new ArrayList<Integer>(nums));
  9.     for (int i = first; i < n; i++) {
  10.       // place i-th integer first
  11.       // in the current permutation
  12.       Collections.swap(nums, first, i);
  13.       // use next integers to complete the permutations
  14.       backtrack(n, nums, output, first + 1);
  15.       // backtrack
  16.       Collections.swap(nums, first, i);
  17.     }
  18.   }

  19.   public List<List<Integer>> permute(int[] nums) {
  20.     // init output list
  21.     List<List<Integer>> output = new LinkedList();

  22.     // convert nums into list since the output is a list of lists
  23.     ArrayList<Integer> nums_lst = new ArrayList<Integer>();
  24.     for (int num : nums)
  25.       nums_lst.add(num);

  26.     int n = nums.length;
  27.     backtrack(n, nums_lst, output, 0);
  28.     return output;
  29.   }
  30. }
复制代码


这个时间复杂度大于n!,小于n*n!,可以去leetcode看一下哈

评分

参与人数 1大米 +3 收起 理由
WarriorZ + 3 很有用的信息!

查看全部评分

回复

使用道具 举报

🔗
WarriorZ 2019-12-9 04:08:37 | 只看该作者
全局:
超人96825 发表于 2019-12-9 01:45
hi,我的理解来看,这个解法时间复杂度不是n!,而是O(n * n!)。

leetcode里给出的solution提供了这个 ...

又学到了,你贴的代码应该是略优于之前那个算法的,但是时间复杂度我谨慎的质疑一下,每次生成一个新的结果的时候需要把原先的list复制到答案里面去,这一步的时间复杂度是O(n)的,一共有n!个答案,所以总的时间复杂度都是O(n*n!)。后面这个算法的系数可能小一点。
回复

使用道具 举报

🔗
basketwang 2020-4-20 11:20:46 | 只看该作者
全局:
哎呀,不好意思,录题时候没太注意代码的部分,下面小伙伴说的对,感谢大家指出啊
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表