简体   繁体   中英

Permutations of a set of data in Java

I have 10,000 items in a set whereby each must be made into triads. I need an algorithm to efficiently find each triad.

For example:

{A,B,C,D,...}

1.AAA 2.AAB 3.AAC 4.AAD ...

all the way to ZZY, ZZZ.

The method I'm using is very inefficient, I created a nested forloop of 3 which iterates through an array, which has a run-time of O(N^3) and terrible on performance obvious. Which kind of algo and data structure would be better for this? Thank you

Function to print all permutations of K length from a set of n characters with repetition of characters:

static void printKLengthPerm(char[] set, String prefix, int n, int k) 
{ 
    if (k == 0) 
    { 
        System.out.println(prefix); 
        return; 
    } 

    for (int i = 0; i < n; i++) 
    { 
        String newPrefix = prefix + set[i]; 
        printKLengthPerm(set, newPrefix, n, k - 1); 
    } 
}

Calling the function to print all permutations of 3 length from a set all capital english alphabets:

char[] set = new char[26]; 
for(int i = 0; i < 26; i++)
  set[i] = (char)(i+65);
int n = set.length; 
printKLengthPerm(set, "", n, 3); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM