您的位置:首页 > 其它

个人记录-LeetCode 47. Permutations II

2016-12-14 20:22 507 查看
问题:

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],
[2,1,1]
]


代码示例:

与LeetCode 46一样,采用全排列的方式即可:

public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();

if (nums == null || nums.length < 1) {
return result;
}

//将数组排序,这样相同的数字排在一起,可以跳过,避免重复结果
Arrays.sort(nums);

//flag记录一个数字是否被选择过
boolean[] flag = new boolean[nums.length];

//path记录每次排列的结果
List<Integer> path = new ArrayList<>();

//无脑暴力递归
permute(nums, path, flag, result);

return result;
}

private void permute(int[] nums, List<Integer> path, boolean[] flag, List<List<Integer>> result) {
//已经完成了所有位置的选择,返回结果
if (path.size() == nums.length) {
result.add(path);
return;
}

boolean first = true;
//prev记录当前位置,上一次选择的数
int prev = -1;

for (int i = 0; i < nums.length; ++i) {
if (!flag[i]) {
if (first) {
prev = nums[i];
first = false;
} else {
//避免在同一个位置,选择相同的数,避免重复
if (nums[i] == prev) {
continue;
}

prev = nums[i];
}

//生成新的位图
List<Integer> tempList = new ArrayList<>(path);
boolean[] tempFlag = new boolean[nums.length];
System.arraycopy(flag, 0, tempFlag, 0, nums.length);

//添加本次信息
tempFlag[i] = true;
tempList.add(nums[i]);

//继续递归
permute(nums, tempList, tempFlag, result);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: