本文主要是介绍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子表都会是空。
这篇关于Remove和RemoveLast用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!