How can I implement a generic algorithm which generates all possible permutations of a string or array elements ?