gpt4 book ai didi

algorithm - 排列二、递归去重

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:18:17 25 4
gpt4 key购买 nike

给定一个包含重复数字的数字列表。找到所有唯一的排列。

For numbers [1,2,2] the unique permutations are:
[
[1,2,2],
[2,1,2],
[2,2,1]
]

在称为 hepler 的方法中,为了删除重复项,我有一个 if 语句:

if (i != 0 && nums[i] == nums[i-1] && !set.contains(i-1) ) {
continue;
}

但我发现如果我将 !set.contains(i - 1) 更改为 set.contains(i-1) 它仍然是正确的(leetcode accepted) , 但它应该是 !set.contains(i - 1)

有人知道原因吗?

class Solution {
/**
* @param nums: A list of integers.
* @return: A list of unique permutations.
*/
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();

if (nums == null) {
return list;
}

if (nums.length == 0) {
list.add( new ArrayList<Integer>() );
return list;
}

Arrays.sort(nums);

HashSet<Integer> set = new HashSet<Integer>();
ArrayList<Integer> current = new ArrayList<Integer>();
helper(nums, list, current, set);

return list;
}

public void helper(int [] nums,
List<List<Integer>> list,
ArrayList<Integer> current,
HashSet<Integer> set){

if(current.size() == nums.length) {
list.add( new ArrayList<Integer>(current) );
return;
}

for (int i = 0; i < nums.length; i++) {

if ( set.contains(i) ) {
continue;
}

if (i != 0 && nums[i] == nums[i-1] && !set.contains(i-1) ) {
continue;
}

current.add( nums[i] );
set.add(i);
helper(nums, list, current, set);
set.remove(i);
current.remove(current.size() - 1);
}
}
}

最佳答案

维基页面描述permutation algorithm to get the next lexicographic permutation ,这适用于重复的元素。伪代码:

Initialisation: 
Start with sorted combination - here [1,2,2]

Next permutation step:

Find the largest index k such that a[k] < a[k + 1]. If no such index exists,
the permutation is the last permutation.

Find the largest index l greater than k such that a[k] < a[l].

Swap the value of a[k] with that of a[l].

Reverse the sequence from a[k + 1] up to and including the final element a[n].

关于algorithm - 排列二、递归去重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40443975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com