|
- #include <iostream>
- #include <vector>
- #include <algorithm>
- std::pair<int, std::vector<int>> findMaxSumBelowLimit(const std::vector<double>& numbers, double limit) {
- std::pair<int, std::vector<int>> bestSumAndCombination{0, {}};
- std::vector<bool> used(numbers.size(), false);
- std::vector<int> combination;
- backtrack(numbers, limit, used, combination, 0, 0, bestSumAndCombination);
- return bestSumAndCombination;
- }
- void backtrack(const std::vector<double>& numbers, double limit, std::vector<bool>& used,
- std::vector<int>& combination, size采用t index, int currentSum,
- std::pair<int, std::vector<int>>& bestSumAndCombination) {
- if (currentSum > limit) {
- return; // 如果当前和大于限制,直接返回
- }
- if (index == numbers.size()) {
- if (currentSum > bestSumAndCombination.first) {
- bestSumAndCombination.first = currentSum;
- bestSumAndCombination.second = combination;
- }
- return;
- }
- // 不选当前数
- backtrack(numbers, limit, used, combination, index + 1, currentSum, bestSumAndCombination);
- // 选当前数
- if (!used[index]) {
- used[index] = true;
- combination.push采用back(index);
- backtrack(numbers, limit, used, combination, index + 1, currentSum + static采用cast<int>(numbers[index]), bestSumAndCombination);
- used[index] = false;
- combination.pop采用back();
- }
- }
- int main() {
- std::vector<double> numbers = {1, 2, 5, 16.3, 22.7, 32.6, 40, 53.1};
- double limit = 100;
-
- auto result = findMaxSumBelowLimit(numbers, limit);
-
- std::cout << "The maximum sum within the limit is: " << result.first << std::endl;
- std::cout << "The combination with this sum is: [";
- for (size采用t i : result.second) {
- std::cout << numbers[i] << " ";
- }
- std::cout << "]" << std::endl;
- return 0;
- }
复制代码 |
|