我必須編寫一個程序,它接受字符串參數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的示例 – Max
'dcb'是一個有效的序列還是必須對應於字符串參數的給定順序? – pjwilliams
@Max:aba,abc,abd,bac,bad等。我想這個問題的描述不是很明顯,但這就是我所擁有的。 – Nath