我的目標是找到所有可能的總和的總和。 例如,如果陣列是 2 59 3 43 5 9 8 62 10 4,如果總爲12,則可能的組合是如何找到所有匹配的數字,在給定的數組中的總和爲'N'
2 10
3 9
8 4
5 3 4
這裏是第一組碼,即我已經寫。想知道在這方面可以做的最好的改進。
int find_numbers_matching_sum(int *number_coll, int total)
{
int *search_till = lower_bound(number_coll,number_coll+TOTAL_SIZE, total);
int location = search_till - number_coll;
if (*search_till > total && location > 0)
{
--location;
}
while (location >= 0)
{
find_totals(number_coll,total,location);
--location;
}
return 1;
}
int find_totals(int *number_coll, int total, int end_location)
{
int left_ones = total - number_coll[end_location];
int curloc = end_location;
int *search_till = 0;
int location ;
int all_numbers[10];
int i = 0;
all_numbers[i] = number_coll[end_location];
while (left_ones && curloc >= 0)
{
search_till = lower_bound(number_coll,number_coll+end_location, left_ones);
location = search_till - number_coll;
if (*search_till > left_ones && location > 0)
{
--location;
}
else if (left_ones < *search_till)
{
break;
}
curloc=location;
left_ones = left_ones - number_coll[curloc];
all_numbers[++i] = number_coll[curloc];
end_location = curloc - 1;
}
if (!left_ones)
{
while (i>=0)
{
cout << all_numbers[i--] << ' ';
}
}
cout << endl;
return 1;
}
使用'lower_bound()'你似乎假設集合是有序的?負數是否允許? – 2010-07-21 19:07:45
在此解決方案中,我正在對數字進行排序,然後調用該函數。 但有沒有更好的方法? – user373215 2010-07-21 19:12:36
http:// stackoverflow的可能重複。com/questions/83547/algorithm-to-find-which-numbers-from-a-list-of-size-n-sum-to-another-number – 2010-07-21 20:48:35