天天看点

java中解决排列组合问题

复现这个例子之前先要导入依赖:

<dependency>
            <groupId>org.raistlic.lib</groupId>
            <artifactId>commons-core</artifactId>
            <version>1.4</version>
 </dependency>
           

运行如下代码:

package com.zhang.arrangementselect;

import org.junit.jupiter.api.Test;
import org.raistlic.common.permutation.Permutation;

import java.util.*;

/**
 * @description:产生所有的组合
 * @author: zhangyu
 * @create: 2019-09-26 14:18
 */
public class GenerateTwoNumber {

    @Test
    public void getPermutationFun() {
        List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
        List<List<String>> newList = new ArrayList<>();
        for (List<String> p : Permutation.of(list)) {
            System.out.println(p);
            newList.add(p);
        }
        System.out.println(newList);
    }
}
           

 返现运行结果:

[a, b, c]
[a, c, b]
[b, a, c]
[b, c, a]
[c, a, b]
[c, b, a]
[[c, b, a], [c, b, a], [c, b, a], [c, b, a], [c, b, a], [c, b, a]]

Process finished with exit code 0
           

这种问题比较诡异,因为它没有复制,只是迭代遍历了数组:

要这种修改,把值复制出来:

package com.zhang.arrangementselect;

import org.junit.jupiter.api.Test;
import org.raistlic.common.permutation.Permutation;

import java.util.*;

/**
 * @description: 产生两个不同的数字
 * @author: zhangyu
 * @create: 2019-09-26 14:18
 */
public class GenerateTwoNumber {

    @Test
    public void getPermutationFun() {
        List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
        List<List<String>> newList = new ArrayList<>();
        for (List<String> p : Permutation.of(list)) {
            System.out.println();
            newList.add(new ArrayList<>(p));
        }
        System.out.println(newList);
    }
}
           

运行结果:

[a, b, c]
[a, c, b]
[b, a, c]
[b, c, a]
[c, a, b]
[c, b, a]
[[a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]]
           

把那个对象复制出现就好了,不会出现一直迭代的问题。因此就解决了排列的问题。