Skip to main content

Command Palette

Search for a command to run...

DSA Important Points

Published
•2 min read•View as Markdown
H

I am a engineering student who's determined to change the time ahead .

In the code for printing subsets of a string, the difference lies in the nature of the problem. In the subset problem, you are dealing with combinations of characters, and the order of the characters doesn't matter. Therefore, you can include or exclude a character at a specific index without worrying about backtracking.

Let's break down the key parts of the PrintSubsets code:

javaCopy codestatic void fn(String str, int index, String ans) {
    // base case.
    if (index == str.length()) {
        System.out.println(ans);
        return;
    }

    // rec case.
    // include the current character in the subset
    fn(str, index + 1, ans + str.charAt(index));

    // exclude the current character from the subset
    fn(str, index + 1, ans);
}

In this code, you have two recursive calls:

  1. The first one includes the current character (ans + str.charAt(index)) and moves to the next index (index + 1).

  2. The second one excludes the current character and also moves to the next index.

Since the order of characters doesn't matter in the subset problem, you can freely explore both possibilities without worrying about backtracking.

In contrast, in the dice target sum problem, you need to keep track of the choices made so far (the dice values) and backtrack when needed. The order of the dice values matters, and you want to explore different combinations of values that lead to the target sum. Hence, you need to handle backtracking to explore different branches of the recursion correctly.

More from this blog

Harsehrawat's blog

52 posts