[LeetCode]Permutations
来源:互联网 发布:索引超出了数组界限 编辑:程序博客网 时间:2024/06/05 04:42
Question
Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
本题难度Medium。
【复杂度】
时间 O(N!) 空间 O(N)
【思路】
就是用树的方法进行遍历。算法为DFS。
【注意】
1、本题说没有重复的数字(如果有就要进行检查)
2、在写递归程序时候要注意递归返回后有没有引起side effect。如果我不写代码30-31行,就会引起错误。代码26-31行相当于用了一个循环队列来进行各项遍历,遍历完了就恢复到初始状态,所以不会引起side effect。当然也可以这样写:
for(int i=0;i<remains.size();i++){ int n=remains.get(i); //be careful remains.remove(i); preList.add(n); helper(preList,remains,ans); preList.remove(preList.size()-1); remains.insert(i,n); }
不过报错:cannot find symbol: method insert(int,int)
。可能方法名搞错了吧。
【代码】
public class Solution { public List<List<Integer>> permute(int[] nums) { //require List<List<Integer>> ans=new ArrayList<>(); if(nums==null) return ans; int size=nums.length; if(size==0) return ans; List<Integer> remains=new ArrayList<Integer>(),list=new ArrayList<Integer>(); for(int n:nums) remains.add(n); //invariant helper(list,remains,ans); //ensure return ans; } private void helper(List<Integer> preList,List<Integer> remains,List<List<Integer>> ans){ //bound if(remains.size()==0){ List<Integer> list=new ArrayList<Integer>(preList); ans.add(list); return; } for(int i=0;i<remains.size();i++){ int n=remains.get(0);//be careful remains.remove(0); preList.add(n); helper(preList,remains,ans); preList.remove(preList.size()-1); remains.add(n); } }}
0 0
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- LeetCode: Permutations
- LeetCode: Permutations
- [Leetcode] Permutations
- [LeetCode] Permutations
- Leetcode: Permutations
- [Leetcode] Permutations
- [Leetcode] Permutations
- [LeetCode]Permutations
- LeetCode-Permutations
- [leetcode] permutations
- LeetCode - Permutations
- Leetcode: Permutations
- 【leetcode】Permutations
- 【LeetCode】Permutations
- 利用AFNetworking框架去管理从聚合数据上面请求到的数据
- Chandy/Misra解法 解决哲学家就餐问题 java实现
- Linux 性能指标及分析工具
- 侧滑删除
- 使用log4j输出详细错误日志
- [LeetCode]Permutations
- webx-request context功能
- Matlab基本语法和基本操作
- Unity中分层控制模型的显示和隐藏透明以及恢复
- linux 延时及时间函数总结
- sql语句中过滤条件where和having的区别
- 到底什么是EJB详解
- ubuntu环境下搭建操作系统实验平台(Virtualbox和Bochs)
- bug解决(SpringMVC)- 严重: Servlet /SpringMVC threw load() exception