递归和动态规划——字符串的子序列
打印一个字符串的全部子序列, 包括空字符串
在字符串的子序列中,每个字符都包含两种情况,
* 1.该字符在序列中
* 2.该字符不在序列中
解:递归
*base case:当前位置指向字符串的最后一个字符时,返回
所以在递归的过程中分为两种情况:
* 1.该字符在序列中
* 2.该字符不在序列中
public class Print_All_Subsequence { public void printAllSubsequenceStr(String str){ if(str == null || str.length() == 0) return; char[] chars = str.toCharArray(); subStr("", 0, chars); } public void subStr(String subStr, int index, char[] chars){ if(index == chars.length){ System.out.println(subStr); return; } //不要当前位置的字符 subStr(subStr, index + 1, chars); //要当前位置的字符 subStr(subStr + chars[index], index + 1, chars); } public static void main(String[] args){ Print_All_Subsequence print_all_subsequence = new Print_All_Subsequence(); print_all_subsequence.printAllSubsequenceStr( "abcs" ); } }