这是我从老师那里得到的这项工作我很想居民,我为此工作了一个星期写一个递归方法签名它 -public void printSubs (String s) - 字符串 s 中的方法参数。该方法打印您可以构建 s 单词的所有字母,每个长度(从一百到所有字母),当单词中字母的顺序必须与它们在 s 中的排列一样时。例如,如果 s = "bye" 方法打印以下字符串:"B"、"y"、"e"、"by"、"ye"、"be"、"bye"如果 s = "home" 系统打印以下字符串:"H"
, "o", "m", "e", "ho", "om", "me", "hm", "he", "oe", "hom", "ome", "hme", hoe ", home "这是我写的:
private String printSubs(String s, String a)
{
if(s.length()==0)
{
return a+"";
}
return printSubs(s.substring(1), a+s.substring(0,1)) +
", " + printSubs(s.substring(1), a);
}
结果:
bye, by, be, b, ye, y, e,
import java.util.ArrayList;
import java.util.List;
public class Test20170118 {
public static void main(String[] args) {
String s = "esempio";
List<String> result = new ArrayList<>();
result.add("");
System.out.println(method(s, result));
System.out.println(method(s, result).size());
}
private static List<String> method(String input, List<String> done){
List<String> result = new ArrayList<>();
if(input.length() == 1){
for (String string : done) {
result.add(string);
result.add(string + input);
}
return result;
} else {
for (String string : done) {
result.add(string);
result.add(string + input.substring(0, 1));
}
return method(input.substring(1), result);
}
}
}