ในปัญหานี้ เราจะได้รับสตริง และต้องพิมพ์ subsequences ทั้งหมดของสตริง Substring จะถูกสร้างโดยการลบองค์ประกอบ และลำดับของสตริงไม่ควรเปลี่ยนแปลง
ตัวอย่างเพื่อความเข้าใจ
Input: string = "xyz" Output: x y xy z xz yz xyz
เพื่อแก้ปัญหานี้ เราจะหา substring ทั้งหมดเริ่มจากการแช่แข็งตัวอักษรแรกของสตริงและหา subsequence ตามลำดับ แล้วค่อยไปตัวอักษรถัดไปในสตริงและ subsequence
โปรแกรมตัวอย่าง
public class Main {
public static void printSubString(String sub, String subSeq) {
if (sub.length() == 0) {
System.out.print(subSeq + " ");
return;
}
char ch = sub.charAt(0);
String ros = sub.substring(1);
printSubString(ros, subSeq);
printSubString(ros, subSeq + ch);
}
public static void main(String[] args) {
String str = "wxyz";
System.out.println("The subStrings are :");
printSubString(str, "");
}
}
ผลลัพธ์
The subStrings are -
z y yz x xz xy xyz w wz wy wyz wx wxz wxy wxyz