标签:i++ length html ++ std -- sig pre targe
给定N个数,从中找出若干个数,使得这些数的和等于sum。
void TwoSum(int data[], unsigned int length, int sum) { std::sort(data, data + length); int begin = 0; int end = length - 1; while (begin < end) { int cur_sum = data[begin] + data[end]; if (cur_sum == sum) { printf("%d %d\n", data[begin], data[end]); begin++; end--; } else { if (cur_sum < sum) begin++; else end--; } } }
0-1背包问题。
void MultiSum(int data[], unsigned int length, int sum, bool flag[], int flag_size) { if (length <= 0 || sum <= 0) return; if (sum == data[length - 1]) { for (int i = 0; i < flag_size; i++) { if (flag[i] == 1) printf("%d+", data[i]); } printf("%d\n", data[length - 1]); } flag[length - 1] = 1; MultiSum(data, length - 1, sum - data[length - 1],flag, flag_size); flag[length - 1] = 0; MultiSum(data, length - 1, sum,flag, flag_size); }
参考资料:
标签:i++ length html ++ std -- sig pre targe
原文地址:http://www.cnblogs.com/gattaca/p/7820160.html