我試圖實施一種回溯算法(它應該貫穿給定數量的人並檢查所有可能的對,每對都有一定的分數,目標是找到許多次出現「最大」分數;所以我需要檢查所有可能的解決方案)。如何在回溯中找到所有可能的解決方案
問題是我無法理解如何使我的函數實際上'回溯'...當它找到解決方案時,它會一直回到根。我該如何回到一個我可以嘗試不同的道路的地步,並讓它走上這條道路,而不是再做一次呢?
這是我的代碼,但我知道我的想法可能是錯誤的......這只是我試圖用很多方式來思考它,而我完全迷失在這裏。 感謝您的幫助!
void allPairs (int x, int pref[], bool teamed[], int* max, int score, int numWorkers) {
for (int i=1; i < numWorkers; i++) {
int count = 0;
pairTwo(x, i, pref, teamed, max, score, numWorkers, &count);
}
}
int pairTwo (int x, int y, int pref[], bool teamed[], int* max, int score, int numWorkers, int* howMany) {
if (x >= numWorkers) {
arrToZero(teamed, numWorkers);
return score;
}
else if (x==y) {
if(y < numWorkers-1) {
y = findUnteamed(teamed, y+1, numWorkers);
}
else {
arrToZero(teamed, numWorkers);
return score;
}
}
int pairScore = sumPair(pref, x, y, teamed, numWorkers);
x = findUnteamed(teamed, x, numWorkers);
y = findUnteamed(teamed, 0, numWorkers);
int temp = pairTwo(x, y, pref, teamed, max, score + pairScore, numWorkers, howMany);
teamed[x] = 0; // here I tried to "erase" the last move but it's useless
teamed[y] = 0;
if (temp >= *max) {
max = &temp;
*howMany++;
printf("There are %d optimal pairings:, with a total score of: %d\n", *howMany, *max);
return *max;
}
else {
return -1;
}
}
您對'pairTwo'的遞歸調用必須在循環中檢查所有可能性,'x'和'y'必須迭代所有* unteamed *,而不僅僅是第一次找到。 –