首页 > 代码库 > Permutations II
Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2]
have the following unique permutations:[1,1,2]
, [1,2,1]
, and [2,1,1]
.
答案
public class Solution { public List<Integer> toList(int[] num) { List<Integer> p = new ArrayList<Integer>(num.length); for (int element : num) { p.add(element); } return p; } public void swap(int[] num, int i, int j) { int p = num[i]; num[i] = num[j]; num[j] = p; } public List<List<Integer>> permuteUnique(int[] num) { List<List<Integer>> result = new LinkedList<List<Integer>>(); if (num == null || num.length <= 0) { return result; } Arrays.sort(num); result.add(toList(num)); int i; int j; while (true) { for (i = num.length - 1; i > 0; i-- ) { if (num[i] > num[i - 1]) { break; } } if (i == 0) { break; } for (j = num.length - 1; j > 0; j-- ) { if (num[j] > num[i - 1]) { break; } } swap(num, i - 1, j); j = num.length - 1; while (i < j) { swap(num, i, j); i++ ; j-- ; } result.add(toList(num)); } return result; } }
Permutations II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。