繁体   English   中英

将 ArrayList 添加到 Java 中的 HashSet

[英]Adding ArrayList to HashSet in Java

我的任务是对 output 对某些 n 的所有整数 [1, 2, ..., 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 运行的 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]]

我是 Java 的新手,不胜感激。

编辑:这是下一个排列 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被传递给nextPermutation方法并在方法内部进行修改: sequence.set(j, tempVal); . 因此,每次调用nextPermutation方法时都会修改原始排列( 通过共享调用)。

但是,您可以轻松地调整代码以在方法内创建列表的副本:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM