在Java中重复排列数组

时间:2012-10-31 12:10:22

标签: java arrays recursion permutation

网站上有一些类似的问题已经提供了一些帮助,但我不能完全解决这个问题,所以我希望这不是重复的。

这是一个家庭作业,你有一组字符[A,B,C],并且必须使用递归来获得所有的排列(重复)。我的代码有点这样做:

char[] c = {'A', 'B' , 'C'};

public void printAll(char[] c, int n, int k) {
    if (k == n) {
      System.out.print(c);
      return;
    }
    else {   
      for (int j = 0; j<n; j++) {
        for (int m = 0; m<n; m++) {
           System.out.print(c[k]); 
           System.out.print(c[j]); 
           System.out.print(c[m] + "\r\n");
        }
      }
    }        
    printAll(c, n, k+1);    
}

然而,参数n应该定义输出的长度,所以虽然这个函数打印出长度为3的所有排列,但它不能用长度为2的那些排列。我已经尝试了我能想到的一切,并且已经仔细考虑了谷歌搜索结果,我自己因为无法解决看似简单的问题而加剧了。

4 个答案:

答案 0 :(得分:7)

如果我理解正确,您将获得一组字符c和所需的长度n

从技术上讲,没有重复排列的东西。我假设您希望所有长度为n的字符串都包含来自c的字母。

你可以这样做:

to generate all strings of length N with letters from C
 -generate all strings of length N with letters from C
     that start with the empty string.

to generate all strings of length N with letters from C
   that start with a string S
 -if the length of S is N
  -print S
 -else for each c in C
  -generate all strings of length N with letters from C that start with S+c

在代码中:

printAll(char[] c, int n, String start){
  if(start.length >= n){
    System.out.println(start)
  }else{
    for(char x in c){ // not a valid syntax in Java
      printAll(c, n, start+x);
    }
  }
}

答案 1 :(得分:3)

我使用这种重复排列的java实现。 A~(n,m):n =阵列长度,m = k。 m可以大于或小于n。

public class Permutations {


    static void permute(Object[] a, int k, PermuteCallback callback) {
        int n = a.length;

        int[] indexes = new int[k];
        int total = (int) Math.pow(n, k);

        Object[] snapshot = new Object[k];
        while (total-- > 0) {
            for (int i = 0; i < k; i++){
                snapshot[i] = a[indexes[i]];
            }
            callback.handle(snapshot);

            for (int i = 0; i < k; i++) {
                if (indexes[i] >= n - 1) {
                    indexes[i] = 0;
                } else {
                    indexes[i]++;
                    break;
                }
            }
        }
    }

    public static interface PermuteCallback{
        public void handle(Object[] snapshot);
    };

    public static void main(String[] args) {
        Object[] chars = { 'a', 'b', 'c', 'd' };
        PermuteCallback callback = new PermuteCallback() {

            @Override
            public void handle(Object[] snapshot) {
                for(int i = 0; i < snapshot.length; i ++){
                    System.out.print(snapshot[i]);
                }
                System.out.println();
            }
        };
        permute(chars, 8, callback);
    }

}

示例输出

aaaaaaaa
baaaaaaa
caaaaaaa
daaaaaaa
abaaaaaa
bbaaaaaa
...
bcdddddd
ccdddddd
dcdddddd
addddddd
bddddddd
cddddddd
dddddddd

答案 2 :(得分:1)

我刚才有个主意。如果你添加了一个隐藏的字符(隐藏的H)[A,B,C,H],然后完成它的所有固定长度排列(你说你知道怎么做)。然后当你把它读掉时,你停在隐藏的角色,例如[B,A,H,C]将变为(B,A)。

嗯,缺点是您必须跟踪您创建的那些[B,H,A,C]与[B,H,C,A]相同

答案 3 :(得分:1)

这是c#版本,用于生成重复的给定字符串的排列:

(基本思想是 - 长度字符串排列的数量&#39; n&#39;重复次数为n ^ n)。

string[] GetPermutationsWithRepetition(string s)
        {
            s.ThrowIfNullOrWhiteSpace("s");
            List<string> permutations = new List<string>();
            this.GetPermutationsWithRepetitionRecursive(s, "",
                permutations);
            return permutations.ToArray();
        }
        void GetPermutationsWithRepetitionRecursive(string s, string permutation, List<string> permutations)
        {
            if(permutation.Length == s.Length)
            {
                permutations.Add(permutation);
                return;
            }
            for(int i =0;i<s.Length;i++)
            {
                this.GetPermutationsWithRepetitionRecursive(s, permutation + s[i], permutations);
            }
        }

以下是相应的单元测试:

[TestMethod]
        public void PermutationsWithRepetitionTests()
        {
            string s = "";
            int[] output = { 1, 4, 27, 256, 3125 };
            for(int i = 1; i<=5;i++)
            {
                s += i;
                var p = this.GetPermutationsWithRepetition(s);
                Assert.AreEqual(output[i - 1], p.Length);
            }
        }