Every combination of character array

后端 未结 1 1905
既然无缘
既然无缘 2020-12-17 07:00

Having problems trying to show every combination of a character of array without repeating letters.

public static String[] getAllLists(String[] elements, int         


        
相关标签:
1条回答
  • 2020-12-17 07:35

    Here's an example implementation. Essentially it takes a String and iterates over every character, putting that character at the front. It then recurses on the remaining characters. That structure removes your issue of repeated letters, because the input to the recursion has removed the character you've already used.

    I also stored results in a set to remove semantic equivalences. The input 'aab' can switch char 0 and char 1 but still be 'aab.' I used a TreeSet to preserve ordering for easier verification of the output, but HashSet would be faster.

      public static Set<String> permute(String chars)
      {
        // Use sets to eliminate semantic duplicates (aab is still aab even if you switch the two 'a's)
        // Switch to HashSet for better performance
        Set<String> set = new TreeSet<String>();
    
        // Termination condition: only 1 permutation for a string of length 1
        if (chars.length() == 1)
        {
          set.add(chars);
        }
        else
        {
          // Give each character a chance to be the first in the permuted string
          for (int i=0; i<chars.length(); i++)
          {
            // Remove the character at index i from the string
            String pre = chars.substring(0, i);
            String post = chars.substring(i+1);
            String remaining = pre+post;
    
            // Recurse to find all the permutations of the remaining chars
            for (String permutation : permute(remaining))
            {
              // Concatenate the first character with the permutations of the remaining chars
              set.add(chars.charAt(i) + permutation);
            }
          }
        }
        return set;
      }
    

    Example run:

      public static void main(String[] args)
      {
        for (String s : CharPermuter.permute("abca"))
        {
          System.out.println(s);
        }
      }
    

    Generates:

    aabc
    aacb
    abac
    abca
    acab
    acba
    baac
    baca
    bcaa
    caab
    caba
    cbaa
    
    0 讨论(0)
提交回复
热议问题