【发布时间】:2020-05-01 12:41:25
【问题描述】:
我的任务是实现一个蛮力算法来输出整数 [1, 2, ..., n] 的所有排列,对于一些 n。但是,我似乎在将 ArrayList 对象添加到 HashSet 时遇到了一些问题:
static Set<List<Integer>> allPermutations(int n){
if(n<=0){throw new IllegalArgumentException();}
List<Integer> thisPermutation = new ArrayList<Integer>();
for(int i=1; i<=n; i++){
thisPermutation.add(i);
}
Set<List<Integer>> allPermutations = new HashSet<List<Integer>>();
while(true){
allPermutations.add(thisPermutation);
thisPermutation = nextPermutation(thisPermutation);
if(thisPermutation == null){break;}
}
return allPermutations;
}
我发现对“nextPermutation”的连续调用确实找到了所有排列,但我不明白当我将排列添加到 HashSet 'allPermutations' 时会发生什么。我在 n=3 下运行的输出是这样的:
[[3, 2, 1, 1, 2, 1, 1, 3, 1, 2], [3, 2, 1], [3, 2, 1, 1, 2, 1, 1], [3, 2, 1, 1], [3, 2, 1, 1, 2, 1, 1, 3, 1], [3, 2, 1, 1, 2, 1]]
我是 Java 新手,希望能得到任何帮助。
编辑:这是 nextPermutation 函数:
static List<Integer> nextPermutation(List<Integer> sequence){
int i = sequence.size() - 1;
while(sequence.get(i) < sequence.get(i-1)){
i -= 1;
if(i == 0){
return null;
}
}
int j = i;
while(j != sequence.size()-1 && sequence.get(j+1) > sequence.get(i-1)){
j += 1;
}
int tempVal = sequence.get(i-1);
sequence.set(i-1, sequence.get(j));
sequence.set(j, tempVal);
List<Integer> reversed = new ArrayList<Integer>();
for(int k = sequence.size()-1; k>=i; k--){
reversed.add(sequence.get(k));
}
List<Integer> next = sequence.subList(0, i);
next.addAll(reversed);
return next;
}
【问题讨论】:
-
nextPermutation实现似乎有问题。也分享这个功能 -
能否也分享一下
nextPermutation方法。