LeetCode:Permutations
来源:互联网 发布:达内科技 php培训 编辑:程序博客网 时间:2024/06/05 13:28
Given a collection of 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]
, and [3,2,1]
.
是道搜索题,这种类型的题目在LeetCode有几道。
package leetcode;import java.util.ArrayList;import java.util.Arrays;public class Permutations {public ArrayList<ArrayList<Integer>> permute(int[] num) {ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();if (num == null || num.length == 0) {return result;}boolean[] flag = new boolean[num.length];Arrays.fill(flag, false);int[] pos = new int[num.length];Arrays.fill(pos, -1);int index = 0;while (index >= 0) {int oldP = pos[index];pos[index]++;while (pos[index] < num.length && flag[pos[index]]) {pos[index]++;}int p = pos[index];if (p == num.length) {//backif (oldP != -1) {flag[oldP] = false;}if (index - 1 >= 0) {flag[pos[index - 1]] = false;}index--;} else {if (!flag[p]) {flag[p] = true;if (index == num.length - 1) {ArrayList<Integer> r = new ArrayList<Integer>(num.length);for (int pp : pos) {r.add(num[pp]);}result.add(r);//find a new resultflag[p] = false;} else {index++;pos[index] = -1;}}}}return result;}}
- 【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
- MFC的图片按钮
- VB遇报表
- 一些技术问题
- RSA hdu 1211 数论的水题(数据较弱)
- C#多线程学习(三) 生产者和消费者
- LeetCode:Permutations
- 101 个 MySQL 的调节和优化的提示
- abc类地址是如何划分的? (转)
- Tomcat6.0虚拟目录配置
- 2013-10-14任务分配
- C#多线程学习(四) 多线程的自动管理(线程池)
- WCS表关联信息url
- 完成端口(I/O completion)原理收藏
- C# Tips: ICloneable<T>