打印一个字符串的全部子序列,包括空字符串

子序列顺序不能变

输入:

abc

输出:

// 第一个是空串

c

b

bc

a

ac

ab

abc

代码:

public class AllStub {

    public static void main(String [] args) {

        String s = "abc";

        printAllSub(s);

    }

        private static void printAllSub(String s) {

            if (s == null) return;

            char[] chars = s.toCharArray();

            if (chars.length>0) {

                String pre = new String("");

                printAllSub(0, pre, chars);

            } else {

                System.out.println("");

            }

        }

        private static void printAllSub(int i, String pre, char[] chars) {

            if (i == chars.length) {

                System.out.println(pre);

                return;

            }

            if (i >chars.length) return;

            printAllSub(i+1, pre,chars);

            printAllSub(i+1, pre+String.valueOf(chars[i]), chars);

        }

}

你可能感兴趣的:(打印一个字符串的全部子序列,包括空字符串)