Skip to content

Add 0039 #193

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions md/0039.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
ข้อนี้จะเป็นการประยุกต์การสร้างลำดับการเรียงสับเปลี่ยน (permutation) โดยพื้นฐานแล้ว ฟังก์ชั่นเรียงตัวเองนี้จะแสดงผลทุกลำดับการเรียงสับเปลี่ยนของตัวเลข $1 - N$ เมื่อเรียกฟังก์ชั่นด้วย `generate_full_permutation({}, n)`

```cpp
void generate_full_permutation(vector<int> permutation, int n) {
if (permutation.size() == n) {
for (auto element : permutation) printf("%d ", element);
printf("\n");
return;
}
for (int i = 1; i <= n; i++) {
if (find(permutation.begin(), permutation.end(), i) != permutation.end()) continue;
permutation.push_back(i);
generate_full_permutation(permutation, n);
permutation.pop_back();
}
}
```

นั่นเพราะว่าฟังก์ชั่นจะเติมตัวเลขที่ไม่ซ้ำกับที่มีอยู่ไปหนึ่งตัว แล้วเรียกตัวเองซ้ำเพื่อเติมเลขอีก จนตัวเลขเต็ม ฟังก์ชั่นจะแสดงตัวเลขที่เก็บไว้ สังเกตว่าทุกลำดับการเรียงสับเปลี่ยนจะถูกแสดงผล และจะแสดงผลตามลำดับทางดิกชั่นนารี (lexicographical order)

จากนั้นเราจะรับอาหารที่ไม่สามารถเสิร์ฟเป็นชนิดแรก และเรียกฟังก์ชั่นสร้างลำดับการเรียงสับเปลี่ยนโดยใส่ตัวแรกเฉพาะตัวที่เป็นไปได้ นั่นคือ
```cpp
for (int i = 1; i <= n; i++) {
if (not_first[i]) continue;
vector<int> permutation = {i};
generate_full_permutation(permutation, n); // ใส่ค่าตัวแรกลงไป
}
```