Remove和RemoveLast用法

LeetCode 46 全排列

先贴代码

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> temp = new ArrayList<>();
    public List<List<Integer>> permute(int[] nums) {
        dfs(nums, 0);
        return result;

    }

    public void dfs(int[] nums, int deep) {
        if(deep == nums.length) {
            result.add(new ArrayList(temp));
            return;
        }

        for(int i=0;i<nums.length;i++) {
            if(!temp.contains(nums[i])) {
                temp.add(nums[i]);
                deep++;
                dfs(nums, deep);
                temp.remove(temp.size()-1);    //LinKedList和ArrayList都可以用该方法
                //temp.remove(Integer.valueOf(nums[i]));
                //temp.removeLast();     //仅有LinkedList可用该方法
                deep--;
            }

        }
    }
}

刷代码随想录回溯算法的时候,经常会想到为什么temp都是用LinkedList的数据结构?

为什么我不能用ArrayList呢?

经过实践证明,ArrayList是可行的

但是有几个注意事项:

1、使用temp.remove(); 删除元素时,要么填入索引值,要么传入对象!而不是nums[i]这个值。

跟add方法是不一样的!

2、ArrayList和LinkedList都有contains()方法和remove()方法

3、即便你使用了ArrayList的数据结构,并不代表你在每次在result添加新的List子表,不用重新new一个ArrayList了,因为List指向的是地址,而不是实际的值,你必须重新new一个ArrayList来保存数据,不然会所有的List子表都会是空。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值