阵列的排列,有重复,在Java中 [英] Permutation of an array, with repetition, in Java

查看:250
本文介绍了阵列的排列,有重复,在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There are some similar questions on the site that have been of some help, but I can't quite nail down this problem, so I hope this is not repetitive.

这是,你有字符[A,B,C]的一组阵列,并且必须使用递归以获得所有排列(含重复)家庭作业。在code我有几分做到这一点:

This is a homework assignment where you have a set array of characters [A, B, C], and must use recursion to get all permutations (with repetition). The code I have sort of does this:

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.我已经试过所有我能想到的,并已看了又看谷歌搜索结果,而我用加重对自己不能够解决什么似乎是一个相当简单的问题。

However, the parameter n should define the length of the output, so while this function prints out all permutations of length 3, it cannot do them of length 2. I have tried everything I can think of, and have pored over Google search results, and I am aggravated with myself for not being able to solve what seems to be a rather simple problem.

推荐答案

如果我理解正确的话,您将得到一组字符 C 和所需的长度 N

If I understand correctly, you are given a set of characters c and the desired length n.

从技术上讲,有没有这样的东西有重置换。我假设你想要的长度的所有字符串 N 号C

Technically, there's no such thing as a permutation with repetition. I assume you want all strings of length n with letters from 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

在code:

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);
    }
  }
}

这篇关于阵列的排列,有重复,在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆