【发布时间】:2011-10-04 22:17:55
【问题描述】:
我必须编写一个程序,它接受字符串参数 s 和整数参数 k 并打印出长度为 k 的 s 的所有子序列。例如,如果我有
subSequence("abcd", 3);
输出应该是
abc abd acd bcd
我需要指导。请不要代码!
提前致谢。
更新:
我正在考虑使用这个伪代码:
Start with an empty string
Append the first letter to the string
Append the second letter
Append the third letter
Print the so-far build substring - base case
Return the second letter
Append the fourth letter
Print the substring - base case
Return the first letter
Append the third letter
Append the fourth letter
Print the substring - base case
Return third letter
Append the second letter
Append the third letter
Append the fourth letter
Print the substring - base case
Return the third letter
Return the second letter
Append the third letter
Append the fourth letter
Return third letter
Return fourth letter
Return third letter
Return second letter
Return first letter
不同的缩进意味着在递归调用中更深入。
(回应迭戈塞维利亚):
按照您的建议:
private String SSet = "";
private String subSequence(String s, int substr_length){
if(k == 0){
return SSet;
}
else{
for(int i = 0; i < substr_length; i++){
subString += s.charAt(i);
subSequence(s.substring(i+1), k-1);
}
}
return SSet;
}
}
【问题讨论】:
-
独特的子序列?例如,给 abacd 举例
-
dcb是有效序列还是必须与字符串参数的给定顺序相对应? -
@Max: aba、abc、abd、bac、bad 等。我想问题的描述不是很解释,但这就是我所拥有的。
-
你确定你说的是子序列而不是子集?子序列只能包含连续的字母。