列出所有排列和放大器;在整型数组列表递归组合递归、组合、放大器、数组

由网友(悲傷在泛濫つ)分享简介:我有一个方法 perm1 的打印所有排列/字符的字符串组合I have a method perm1 that prints all permutations/combinations of characters in a string// print permutation / combination of th...

我有一个方法 perm1 的打印所有排列/字符的字符串组合

I have a method perm1 that prints all permutations/combinations of characters in a string

// print permutation / combination of the characters of the string s (in order)
public  static void perm1(String s) { perm1("", s); }
private static void perm1(String prefix, String s) {
    int N = s.length();
    if (N == 0) System.out.println(prefix); 
    else {
        System.out.println(prefix);
        for (int i = 0; i < N; i++)
           perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
    }
}

perm1 工作确定并产生所需的输出。

perm1 works OK and produces the desired output.

我想创建一个类似的方法 perm2 在整数的ArrayList

I am trying to create a similar method perm2 that works on an arraylist of Integers

public static void perm2(ArrayList<Integer> a) {
    ArrayList<Integer> sub = new ArrayList<Integer>(); 
    perm2(sub, a);
}
public static void perm2(ArrayList<Integer> sub, ArrayList<Integer> a){
    int L = a.size();
    if (L==0) System.out.println(sub);
    else {
        System.out.println(sub);
        for (int i = 0; i < L; i++){
            sub.add(a.get(i));
            a.remove(i);
            perm2(sub, a);
            L = a.size(); // to avoid Index out of bounds exception
        }           
    }
}

这不会产生所有的排列组合,因为我希望。使用一个ArrayList [1,2,3],它只能打印以下内容:

This does not generate all the permutations and combinations as I am hoping. Using an arraylist [1, 2, 3], it only prints the following:

[]
[1]
[1, 2]
[1, 2, 3]

谁能告诉我如何修改perm2,使其打印像其他的预期值[2] [3] [2,3] [3,2] [2,3,1] [2,1, 3]等...

Can anyone please tell me how to modify perm2 so that it will print the other expected values like [2] [3] [2, 3] [3, 2] [2, 3, 1] [2, 1, 3] etc...

推荐答案

对于需要 L = a.size()应该已经暗示。 A 的值应该是一个正常运作preserved(它们的位置和值)。

The need for L=a.size() should've been a hint. sub and a values should be preserved (their positions and values) for a proper functioning.

下面code创建数组列表中的新副本,并对它们进行操作:

Below code creates a new copy of the array lists and operates on them:

public static void perm2(ArrayList<Integer> a) {
        ArrayList<Integer> sub = new ArrayList<Integer>();
        perm2(sub, a);
    }

 public static void perm2(ArrayList<Integer> sub, ArrayList<Integer> a) {
     int L = a.size();
     if (L == 0) System.out.println(sub);
     else {
         System.out.println(sub);
         for (int i = 0; i < L; i++) {
             ArrayList<Integer> ab = new ArrayList<Integer>(sub);
             ab.add(a.get(i));
             ArrayList<Integer> bc = new ArrayList<Integer>(a);
             bc.remove(i);
             perm2(ab, bc);
         }
     }
 }
阅读全文

相关推荐

最新文章