Print out all the permutations of a string.
Anonymous
My favorite approach is to use a bitvector. As the best-case complexity is O(n*2^n), it not feasible to permute a large N. An integer (32-bits) or long (64-bits) is good enough. Each bit acts as a flag of whether the character can be shown. Increment and show until the end-point is reached. For example, "abc" has the permutation of: 000 --> ___ 001 --> __c 010 --> _b_ 011 --> _bc 100 --> a__ 101 --> a_c 110 --> ab_ 111 --> abc The code is very simple and lazily evaluated, so it has O(1) space complexity. A gray code counter could be used to have a cleaner output, but that's a nit.
Check out your Company Bowl for anonymous work chats.