简体   繁体   中英

All possible permutations of length k (k legth string ) from a set (array of chars) length n dynamic programming solution

I am looking for a dynamic programming solution of getting all permutations of k length from a set of n unique strings.

Example:

array = {"A","B","C","D","E","F","G"}; // n = 7 example permutations = {ABC}, {ABD}, {ABE} etc // k = 3

I have an approach to solve this, as first to generate combinations, then generate all possible permutations of that combination. Combinations can be generated using dynamic programming like solving Binomial Coefficient problem using DP.

Thoughts?

Here is a start. This will print all possible combinations. I'll let you work on the permutations part. Keep in mind this doesn't include memorization. There may be duplicate recursive calls. You should investigate this further (I don't want to solve your entire homework assignment).

// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
void printCombination(String arr[], int n, int r)
{
    // A temporary array to store all combination one by one
    String[] data = new String[r];

    // Print all combination using temprary array 'data[]'
    combinationUtil(arr, data, 0, n-1, 0, r);
}

/* arr[]  ---> Input Array
data[] ---> Temporary array to store current combination
 start & end ---> Staring and Ending indexes in arr[]
index  ---> Current index in data[]
r ---> Size of a combination to be printed */
void combinationUtil(String arr[], String data[], int start, int end, int index, int r)
{
    // Current combination is ready to be printed, print it
    if (index == r)
    {
        for (int j=0; j<r; j++)
            System.out.printf("%s ", data[j]);
        System.out.printf("\n");
        return;
    }

    // replace index with all possible elements. The condition
    // "end-i+1 >= r-index" makes sure that including one element
    // at index will make a combination with remaining elements
    // at remaining positions
    for (int i=start; i<=end && end-i+1 >= r-index; i++)
    {
        data[index] = arr[i];
        combinationUtil(arr, data, i+1, end, index+1, r);
    }
}

Run this code here

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