Generating all permutations of a given string

To generate all permutations of a given string in Java, you can use a recursive approach.

Here's an example of a recursive function that generates all permutations of a string:

import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    String str = "abc";
    List<String> permutations = generatePermutations(str);
    System.out.println(permutations);  // Outputs: ["abc", "acb", "bac", "bca", "cab", "cba"]
  }

  public static List<String> generatePermutations(String str) {
    List<String> permutations = new ArrayList<>();
    if (str.length() == 0) {
      permutations.add("");
      return permutations;
    }
    for (int i = 0; i < str.length(); i++) {
      char c = str.charAt(i);
      String rest = str.substring(0, i) + str.substring(i + 1);
      List<String> subPermutations = generatePermutations(rest);
      for (String sub : subPermutations) {
        permutations.add(c + sub);
      }
    }
    return permutations;