【LeetCode】46. Permutations
来源:互联网 发布:ubuntu 16.04 17.10 编辑:程序博客网 时间:2024/05/18 04:17
问题链接:https://leetcode.com/problems/permutations/#/description
求数组的全排列
算法
一个个的将每一个数插入数组,如数组[1,2,3]
,设结果二重数组为r
,初始化r
中只有一个数组r=[[1]]
,
然后要插入数据2
,有两种插法,[1,2]
和[2,1]
,即插在1
前面和后面,从而r
里有了两个数组r=[[1,2],[2,1]]
,接下来插入数据3
,对于数组[1,2]
,3
可以插在位置{0,1,2}
,得到三个数组[3,1,2]
和[1,3,2]
和[1,2,3]
,对于数组[2,1]
同样会有三个数组,从而r
中会有6
个数组:r=[[3,1,2],[1,3,2],[1,2,3],[3,2,1],[2,3,1],[2,1,3]]
,就得到了所需结果。
代码
public List<List<Integer>> permute(int[] nums) { List<List<Integer>> r = new ArrayList<>(); if(nums.length == 0) return r; List<Integer> arr = new ArrayList<>(); arr.add(nums[0]); r.add(arr); for(int i=1;i<nums.length;i++) { List<List<Integer>> new_r = new ArrayList<>(); for(List<Integer> l:r) { for(int j=0;j<=i;j++) { List<Integer> tmp = new ArrayList<>(l); tmp.add(j, nums[i]); new_r.add(tmp); } } r = new_r; } return r; }
0 0
- [LeetCode]46.Permutations
- LeetCode 46.Permutations
- 46. Permutations Leetcode Python
- LeetCode --- 46. Permutations
- [Leetcode] 46. Permutations
- [leetcode] 46.Permutations
- LeetCode 46. Permutations DFS
- 46. Permutations LeetCode
- Leetcode 46. Permutations
- leetcode 46. Permutations
- LeetCode *** 46. Permutations
- LeetCode 46. Permutations
- leetcode 46. Permutations
- LeetCode - 46. Permutations
- 【leetcode】46. Permutations
- leetcode 46. Permutations
- [LeetCode] 46. Permutations
- leetcode 46. Permutations
- Scrapy爬虫入门系列2 示例教程
- HTTP与HTTPS的区别
- 剑指offer-面试题50-树中两个结点的最低公共祖先
- 2017-5网页浏览
- 实践一下动态代理
- 【LeetCode】46. Permutations
- jquery的ajax同步和异步
- Opencv4Android之人脸检测与识别
- 深度学习与人脸识别系列(1)__算法流程和教程大纲(基于caffe)
- HoloLens开发——Hololens Spatial mapping(空间映射)中移动子模型后父模型移动的实现方法
- leetcode78subset
- 二叉树操作(面试必备)
- redis集群客户端JedisCluster优化
- WinHttp之获取网站首页源码2