简体   繁体   English

生成ArrayList的所有排列 <String> 给定长度的

[英]Generate all permutations of ArrayList<String> of a given length

I am trying to create an algorithm where the method takes in an ArrayList and the length of the output is specified. 我正在尝试创建一种算法,其中该方法采用ArrayList并指定了输出的长度。 The job of the method is to print all possible permutations of the items os the specified arraylist. 该方法的工作是在指定的数组列表中打印项目的所有可能排列。 For eg, if arraylist is 1,2 and length given is 3, it should give output as 112,122,121,212 例如,如果arraylist为1,2且给定的长度为3,则其输出应为112,122,121,212

The resultant can be built by recursively adding all the possible characters to an existing result until you get to the wished length. 可以通过将所有可能的字符递归添加到现有结果中来构建结果,直到达到所需的长度。 You start with an empty result. 您从空结果开始。 The algorithm for this is pretty easy: 算法很简单:

public static void main(String... arg) {
    int n = 2;
    int l = 3;

    List<String> a = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        a.add(Integer.toString(i+1));
    }
    perm(a, "", l);
}

private static void perm(List<String> a, String result, int l) {
    if (result.length() == l) {
        System.out.println(result);
        return;
    }
    for (int i = 0; i < a.size(); i++) {
        String nr = result + a.get(i);
        perm(a, nr,l );
    }
}

output: 输出:

111
112
121
122
211
212
221
222

try the solutions given here(including the ones in the comment section) 尝试此处提供的解决方案(包括评论部分中的解决方案)

http://www.geeksforgeeks.org/print-all-combinations-of-given-length/ http://www.geeksforgeeks.org/print-all-combinations-of-given-length/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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