解題思路
把已選數字放入 path,並以 start 記錄下一個可選索引。每次只能挑 start 之後的位置,因此同一組數字不會因排列不同而重複出現,也不會選到相同元素兩次。path 長度到 6 時就輸出。
輸入集合已經排序,候選索引也由小到大展開,所以回溯輸出天然就是字典序。若還缺 need 個數字,起點最晚只能是 k−need,超過就不足以選滿,可直接剪枝。k=0 結束;只在相鄰兩筆資料之間印空白行。
Step-by-step animation
示意:集合 1 至 7
步驟 1 / 3
第一條分支
依序選最小六個數字。
1
2
3
4
5
6
- 已選
- 6
- 輸出序號
- 1
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
int main() {
int k;
bool first = true;
while (cin >> k && k) {
vector<int> a(k), path;
for (int &x : a)
cin >> x;
if (!first)
cout << '\n';
first = false;
function<void(int)> dfs = [&](int start) {
if (path.size() == 6) {
for (int i = 0; i < 6; ++i)
cout << (i ? " " : "") << path[i];
cout << '\n';
return;
}
int need = 6 - int(path.size());
for (int i = start; i <= k - need; ++i) {
path.push_back(a[i]);
dfs(i + 1);
path.pop_back();
}
};
dfs(0);
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。