Search code examples
javaalgorithmrecursiondata-structuresbacktracking

Print number of possible non-empty sequences of letters


I want to print number of possible non-empty sequences of letters . Eg.

String str="ABC";

Expected output is

A,B,C
AB,AC,BC,BA,CA,CB
ABC,ACB,BAC,BCA,CAB,CBA`

But i get the below output which is incorrect. How to fix my code

BB CC A AB ACC BC ABC AC B BBC CCC BCC C CBC CB

I have written the below code using Recurion

String tiles = "ABC";
Set<String> ans = new HashSet<>();
solve(tiles, 0, "", ans);

public static void solve(String tiles, int idx, String output, Set<String> ans) {

        ans.add(output);

        if (idx >= tiles.length()) {
            return;
        }

        for (int i = idx; i < tiles.length(); i++) {

            solve(tiles, idx + 1, output + tiles.charAt(i), ans);

        }

    }

This is how recursion tree would look like for str="AAB"


Solution

  • You need to ignore the first passing of the "" from output and then you need to ignore each letter you already passed through

    public static void main(String[] args) {
        String tiles = "ABC";
        List<String> ans = new ArrayList<>();
        solve(tiles, "", ans);
        System.out.println(ans);
    }
    public static void solve(String tiles, String output, List<String> ans) {
        if (!output.equals("")) ans.add(output);
        for (int i = 0; i < tiles.length(); i++) {
            String str = tiles.substring(0, i) + tiles.substring(i + 1);
            solve(str, output + tiles.charAt(i), ans);
        }
    }
    

    Output

    [A, AB, ABC, AC, ACB, B, BA, BAC, BC, BCA, C, CA, CAB, CB, CBA]