Permutation of an array, with repetition, in Java

前端 未结 4 1084
名媛妹妹
名媛妹妹 2021-01-12 01:47

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.

This is a home

4条回答
  •  醉话见心
    2021-01-12 02:19

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

    Technically, there's no such thing as a permutation with repetition. I assume you want all strings of length n with letters from c.

    You can do it this way:

    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
    

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

提交回复
热议问题