C语言多个数字组合相加的和最接近或等于某个数的组合
时间: 2023-05-28 14:07:59 浏览: 87
思路:
1. 首先将所有数字从小到大排序,方便后续计算。
2. 接着从第一个数字开始,依次枚举所有可能的组合情况。
3. 对于每一种组合情况,计算其和与目标值的差值,如果该差值比当前记录的最小差值更接近0,则更新最小差值和对应的组合情况。
4. 最后输出最接近目标值的组合情况和其和。
代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_N 100
int nums[MAX_N];
int n;
void dfs(int cur, int sum, int target, int* min_diff, int* ans) {
if (cur == n) {
int diff = abs(sum - target);
if (diff < *min_diff) {
*min_diff = diff;
for (int i = 0; i < n; i++) {
ans[i] = nums[i];
}
}
return;
}
dfs(cur + 1, sum, target, min_diff, ans);
dfs(cur + 1, sum + nums[cur], target, min_diff, ans);
}
int main() {
int target;
int min_diff = 1e9;
int ans[MAX_N];
scanf("%d %d", &n, &target);
for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
}
dfs(0, 0, target, &min_diff, ans);
printf("sum = %d\n", target - min_diff);
for (int i = 0; i < n; i++) {
if (ans[i]) {
printf("%d ", ans[i]);
}
}
printf("\n");
return 0;
}
```
参考链接:https://www.acwing.com/solution/content/3933/
阅读全文