Permutations
来源:互联网 发布:太阳光谱数据在哪有 编辑:程序博客网 时间:2024/06/11 00:37
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]
.
public class Solution { public List<List<Integer>> permute(int[] nums) { Arrays.sort(nums); List<List<Integer>> ret = new ArrayList<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); boolean[] used = new boolean[nums.length]; helper(ret,list,nums,used); return ret; } private void helper(List<List<Integer>> ret,List<Integer> list,int[] nums, boolean[] used) { if (list.size() == nums.length) { ret.add(new ArrayList<Integer>(list)); return; } for (int i = 0; i < nums.length; i++) { if (used[i])) continue; list.add(nums[i]); used[i] = true; helper(ret, list, nums, used); list.remove(list.size() - 1); used[i] = false; } }}
Permutations 2
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2]
[1,1,2]
, [1,2,1]
, and [2,1,1]
.
use a boolean array to store the status of the elements. If the current element equals the previous one and the previous element has not been visited before, skip current element. for example, if current element is the second 1, it will cause duplicate [1,1,2] and [1,2,1], so we need to skip it.
public class Solution { public List<List<Integer>> permuteUnique(int[] nums) { Arrays.sort(nums); List<List<Integer>> ret = new ArrayList<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); boolean[] visited = new boolean[nums.length]; helper(ret,list,nums,visited); return ret; } private void helper(List<List<Integer>> ret, List<Integer> list, int[] nums, boolean[] visited) { if (list.size() == nums.length) { ret.add(new ArrayList<Integer>(list)); return; } for (int i = 0; i < nums.length; i++) { if (visited[i] || i != 0 && nums[i] == nums[i - 1] && !visited[i - 1]) continue; visited[i] = true; list.add(nums[i]); helper(ret,list,nums,visited); list.remove(list.size() - 1); visited[i] = false; } }}
0 0
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- JSP的<c:choose> <c:forEach> <c:if> <c:when> <c:set>标签
- 第三次作业:网络编程
- 海口割双眼皮
- 关于“预编译”
- 二十种高热量食物
- Permutations
- 99%都答不对的C++问题
- android网络编程-HttpURLConnection(一)
- VC2013中“GetVersionExW函数被声明为已否决”
- 3d数学基础-缩放矩阵,投影矩阵-用C++实现
- h264中avc和flv数据的解析
- 汤原身份证号码户籍地址信息查询
- hadoop参考链接
- 汤原在逃犯罪人员信息记录查询