Algorithm to generate all combinations of a string

前端 未结 10 1934
日久生厌
日久生厌 2021-02-01 22:47

I found a link online that shows an algorithm to generate all combinations of a string: http://www.mytechinterviews.com/combinations-of-a-string

Algorithm is copied belo

10条回答
  •  再見小時候
    2021-02-01 23:11

    Below code is to generate permutation and combination of string, basically the concept is to pick one character at a time:

    public class permutecombo
    {
      static void initiate(String s)
      {
        permute("", s);
        System.out.println("----------------------------------------- ");
        combo("", s);
        System.out.println("----------------------------------------- ");
      }
    
      static void combo(String prefix, String s)
      {
        int N = s.length();
    
        System.out.println(prefix);
    
        for (int i = 0 ; i < N ; i++)
          combo(prefix + s.charAt(i), s.substring(i+1));
      }
      static void permute(String prefix, String s)
      {
        int N = s.length();
    
        if (N == 0)
          System.out.println(" " + prefix);
    
        for (int i = 0 ; i < N ; i++)
          permute(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
      }
    
      public static void main(String[] args)
      {
        String s = "1234";
        initiate(s);
      }
    }
    

提交回复
热议问题