题目:打印一个字符串的全部子序列,包括空字符串
假如该字符串为"abc"则用画图的方式穷举所有可能
代码如下:
public class PrintAllSubsquences {
/**
* 方法一
* @param str
*/
public static void function(String str) {
char[] chs = str.toCharArray();
process(chs, 0, new ArrayList<Character>());
}
/**
* 来到i位置有两条路要与不要
* res为之前走过的路,形成的列表
* @param chs
* @param i
* @param res
*/
public static void process(char[] chs, int i, List<Character> res) {
if(i == chs.length) {
printList(res);
return;
}
List<Character> resKeep = copyList(res);
resKeep.add(chs[i]);//要当前字符
process(chs, i+1, resKeep);
List<Character> resNoInclude = copyList(res);//不要当前字符
process(chs, i+1, resNoInclude);
}
public static void printList(List<Character> res) {
for (Character re : res) {
System.out.print(re);
}
System.out.println();
}
public static List<Character> copyList(List<Character> list){
ArrayList<Character> arrayList = new ArrayList<>();
for (Character character : list) {
arrayList.add(character);
}
return arrayList;
}
/**
* 方法二,省空间,复用了str的空间
* @param str
*/
public static void printAllSubsquence(String str) {
char[] chs = str.toCharArray();
process(chs, 0);
}
public static void process(char[] chs, int i) {
if (i == chs.length) {
System.out.println(String.valueOf(chs));
return;
}
process(chs, i + 1);//要当前字符
char tmp = chs[i];
chs[i] = 0;
process(chs, i + 1);//不要当前字符
chs[i] = tmp;
}
public static void main(String[] args) {
String test = "abc";
// String test = "abcd";
// printAllSubsquence(test);
function(test);
}
}