简体   繁体   中英

Generate all subsequences of length m from a character array of length n where n >= m in Java language

I was looking for an optimal code in Java for generating all subsequences of length m from a character array of length n, where n >= m.

The meaning of subsequence is here: https://en.wikipedia.org/wiki/Subsequence

My current psuedocode/algorithm is below. But it doesn't look optimized.

if (m <= 0)
    return;
for (i = 0; i < 2^n; i++) { // can use BigInteger if n > 64
    j = numberOfBitsSet(i); // assuming numberOfBitsSet is implemented
    if (j == m) {
        s = "";
        while((index = getIndexOfNextBitSet(i)) >= 0) { // assuming getIndexOfNextBitSet is implemented
            s = s + charArray[index]; // bit numbering starts from zero
        } // end of while
        System.out.println(s);
    } // end of if
} // end of for

Usually I solve algorithmic tasks in C++. There is the cool function of next_permutation that allows you to shuffle through all "permutations" of a sequence. If the sequence is say "00110100" next_permutation will give you "00111000" (in optimal way).

I found an example implementation of the same function in java here .

How this can help you solve your problem: initialize a sequence with n - m leading zeroes followed by m ones. Use your mask-base generation. After that do next_permutation . The complexity of this algorithm is n * subsequence_count . This will be significant improvement if you know that m follows certain rules, but once again will trigger huge number of results if n = 64 and m = 32 for example.

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