我剛剛在大學開始學習Backtracking
算法。不知何故,我設法爲Subset-Sum問題製作程序。工作正常,但後來我發現我的程序並沒有給出所有可能的組合。理解子集總和
例如:目標總數可能有一百個組合,但我的程序只給出30. 這裏是代碼。如果有人能指出我的錯誤是什麼,這將是一個很大的幫助。
int tot=0;//tot is the total sum of all the numbers in the set.
int prob[500], d, s[100], top = -1, n; // n = number of elements in the set. prob[i] is the array with the set.
void subset()
{
int i=0,sum=0; //sum - being updated at every iteration and check if it matches 'd'
while(i<n)
{
if((sum+prob[i] <= d)&&(prob[i] <= d))
{
s[++top] = i;
sum+=prob[i];
}
if(sum == d) // d is the target sum
{
show(); // this function just displays the integer array 's'
top = -1; // top points to the recent number added to the int array 's'
i = s[top+1];
sum = 0;
}
i++;
while(i == n && top!=-1)
{
sum-=prob[s[top]];
i = s[top--]+1;
}
}
}
int main()
{
cout<<"Enter number of elements : ";cin>>n;
cout<<"Enter required sum : ";cin>>d;
cout<<"Enter SET :\n";
for(int i=0;i<n;i++)
{
cin>>prob[i];
tot+=prob[i];
}
if(d <= tot)
{
subset();
}
return 0;
}
當我運行程序:
Enter number of elements : 7
Enter the required sum : 12
Enter SET :
4 3 2 6 8 12 21
SOLUTION 1 : 4, 2, 6
SOLUTION 2 : 12
雖然4,8也是一個解決方案,我的程序犯規表現出來。 其輸入數量爲100或更多時更爲糟糕。將有ATLEAST 10000種組合,但我的程序顯示了100
我正努力遵循的邏輯:在主集合中的元素
- 考慮到的一個子集,只要 總和該子集保持小於或等於目標總和。
- 如果在子集合中增加一個特定的數字使得它大於目標,它就不會考慮它。
- 一旦達到設定的結束 和答案還沒有找到,它會從一組最 最近拍攝的數字,並開始尋找在除去最近數的位置後的位置的數字 。 (因爲我存儲在數組''是主要SET中 選定數字的位置)。
如果你的變量有更多的描述性名字(這對你的編程生涯總的來說很有用),或者至少如果你告訴我們每一個應該是什麼意思,它們是如何聲明,初始化等的 – Angew
您可以添加一些示例輸入,您希望輸出的內容以及輸出是什麼。這個代碼如何給出任何東西,或者從哪裏得到輸入,都不是很清楚。 – john
對不起,太模糊了。這是我第一次在網上發佈代碼。 – thekeystroker