Under construction

Still being built. Things may change

String Permutation

Time limit5sMemory limit512 MB

Summary
Print every permutation of a short string of distinct characters, in the order given by the original character positions.
Level

Easy3 of 10

Topics
Backtracking, Recursion, Implementation
Solved
No attempts yet

Problem

Write a recursive function that reads a string and prints all permutations of that string. The string consists of a set of distinct characters.

Input

The first line contains TT (1≤T≤2001 \le T \le 200), the number of test cases. Each of the next TT lines contains one string. Its length LL satisfies 1≤L≤51 \le L \le 5, and it consists of distinct non-whitespace characters.

Output

For each test case, first print a line in the format Case # x:, where x is the test case number starting from 1. Then print the permutations of the string, one per line.

Print the permutations in this order. Choose the first character from the characters of the input string, taking them in the order they appear in the input, and for each choice apply the same rule recursively to the remaining characters. For example, the permutations of abc are printed in the order abc, acb, bac, bca, cab, cba. The order depends on the positions of the characters in the input, not on alphabetical order.

Examples1

  1. Example 1

    Input
    3
    abc
    zxyw
    p7*
    
    Expected output
    Case # 1:
    abc
    acb
    bac
    bca
    cab
    cba
    Case # 2:
    zxyw
    zxwy
    zyxw
    zywx
    zwxy
    zwyx
    xzyw
    xzwy
    xyzw
    xywz
    xwzy
    xwyz
    yzxw
    yzwx
    yxzw
    yxwz
    ywzx
    ywxz
    wzxy
    wzyx
    wxzy
    wxyz
    wyzx
    wyxz
    Case # 3:
    p7*
    p*7
    7p*
    7*p
    *p7
    *7p