[英]Adding ArrayList to HashSet in Java
I was tasked with implementing a brute force algorithm to output all permutations of integers [1, 2, ..., n] for some n.我的任务是对 output 对某些 n 的所有整数 [1, 2, ..., n] 的排列实施蛮力算法。 However, I seem to have some problem with adding ArrayList objects to a HashSet:
但是,将 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;
}
I've discovered that the successive calls to 'nextPermutation' do indeed find all permutations, but I don't understand what happens when I add the permutations to the HashSet 'allPermutations'.我发现对“nextPermutation”的连续调用确实找到了所有排列,但我不明白当我将排列添加到 HashSet 'allPermutations' 时会发生什么。 The output I get on running with n=3 is this:
我用 n=3 运行的 output 是这样的:
[[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]]
[[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]]
I'm new to Java and would appreciate any help.我是 Java 的新手,不胜感激。
Edit: Here's the nextPermutation function:编辑:这是下一个排列 function:
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;
}
List<Integer> sequence
is passed to the nextPermutation
method and modified inside the method: sequence.set(j, tempVal);
List<Integer> sequence
被传递给nextPermutation
方法并在方法内部进行修改: sequence.set(j, tempVal);
. . Thus, the original permutation is modified each time the
nextPermutation
method is called ( Call by sharing ).因此,每次调用
nextPermutation
方法时都会修改原始排列( 通过共享调用)。
However, you could easily adapt your code to create a copy of the list inside the method:但是,您可以轻松地调整代码以在方法内创建列表的副本:
static List<Integer> nextPermutation(final List<Integer> s) {
List<Integer> sequence = new ArrayList<>(s);
int i = sequence.size() - 1;
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.