Skip to content

用递归方式获得一个字符串的全部子序列

  • 同样,对于每个字符 i,都存在两种情况

  • 在子串中

  • 不在子串中

  • 所以可以进行递归

  • 树最上面的一层是第一个字符在或者不在

  • 第二层是第二个字符在或者不在

  • 以此类推

import java.util.*;
class GFG {

    // Declare a global list
    static List<String> al = new ArrayList<>();

    // Creating a public static Arraylist such that
    // we can store values
    // IF there is any question of returning the
    // we can directly return too// public static
    // ArrayList<String> al = new ArrayList<String>();
    public static void main(String[] args)
    {
        String s = "abcd";
        findsubsequences(s, ""); // Calling a function
        System.out.println(al);
    }

    private static void findsubsequences(String s,
                                         String ans)
    {
        System.out.println(s + "|" + ans);

        //判断是不是已经考虑了所有位置
        if (s.length() == 0) {
            al.add(ans);
            return;
        }
        // We add adding 1st character in string
        findsubsequences(s.substring(1), ans + s.charAt(0));

        // Not adding first character of the string
        // because the concept of subsequence either
        // character will present or not
        findsubsequences(s.substring(1), ans);
    }
}
abcd|
bcd|a
cd|ab
d|abc
|abcd
|abc
d|ab
|abd
|ab
cd|a
d|ac
|acd
|ac
d|a
|ad
|a
bcd|
cd|b
d|bc
|bcd
|bc
d|b
|bd
|b
cd|
d|c
|cd
|c
d|
|d
|
[abcd, abc, abd, ab, acd, ac, ad, a, bcd, bc, bd, b, cd, c, d, ]