Permutation คืออะไร?
Permutation คือการจัดเรียงสมาชิกของเซตในลำดับต่างๆ สำหรับสตริงความยาว n มี permutation ทั้งหมด n! แบบ
ตัวอย่างโค้ด (Recursive Backtracking)
public class Demo {
static void printPermutations(String remaining, String prefix) {
// Base case: ไม่มีตัวอักษรเหลือ -> พิมพ์ prefix
if (remaining.length() == 0) {
System.out.print(prefix + " ");
return;
}
// boolean array กันตัวอักษรซ้ำ (สำหรับสตริงที่มีตัวซ้ำ เช่น "aab")
boolean[] used = new boolean[26]; // assuming lowercase a-z
for (int i = 0; i < remaining.length(); i++) {
char ch = remaining.charAt(i);
// ข้ามตัวอักษรที่ใช้ไปแล้วในระดับนี้ (กัน duplicate permutations)
if (used[ch - 'a']) continue;
used[ch - 'a'] = true;
// สร้างสตริงที่เหลือ (ลบตัวที่ i ออก)
String nextRemaining = remaining.substring(0, i) + remaining.substring(i + 1);
// Recursive call: เพิ่ม ch เข้า prefix
printPermutations(nextRemaining, prefix + ch);
}
}
public static void main(String[] args) {
String str = "hey";
System.out.println("Permutations ของ \"" + str + "\":");
printPermutations(str, "");
System.out.println();
}
}
ผลลัพธ์
Permutations ของ "hey": hey hye ehy eyh yhe yeh
คำอธิบายอัลกอริทึม
- Base case: ไม่มีตัวอักษรเหลือ → พิมพ์ prefix (permutation หนึ่งเสร็จ)
- Loop ทุกตำแหน่ง: เลือกตัวอักษรแต่ละตัวเป็นตัวถัดไป
- Skip duplicates: ใช้ boolean array กันการสร้าง permutation ซ้ำ (สำคัญสำหรับสตริงแบบ "aab")
- Recursive call: ส่ง remaining (ลบตัวที่เลือกออก) และ prefix + ch
Trace สำหรับ "abc"
printPermutations("abc", "")
i=0: ch='a', rem="bc" -> printPermutations("bc", "a")
i=0: ch='b', rem="c" -> printPermutations("c", "ab")
i=0: ch='c', rem="" -> PRINT "abc"
i=1: ch='c', rem="b" -> printPermutations("b", "ac")
i=0: ch='b', rem="" -> PRINT "acb"
i=1: ch='b', rem="ac" -> printPermutations("ac", "b")
... -> "bac", "bca"
i=2: ch='c', rem="ab" -> printPermutations("ab", "c")
... -> "cab", "cba"
ความซับซ้อน
| Metric | Complexity |
|---|---|
| Time | O(n × n!) |
| Space (Call Stack) | O(n) |
| Output Size | n! strings |