给定N个数,从中找出若干个数,使得这些数的和等于sum。
TwoSum
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--; } } }
MultiSum
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); }
参考资料:
寻找和为定值的多个数
时间: 2024-10-08 00:19:35