function findIndices(nums, n, target) {\n let result = [];\n let sum = 0;\n let minIndexSum = Infinity;\n\n // 递归函数,用于寻找和为target的n个数的下标\n function backtrack(startIndex, count, currentSum, indices) {\n if (count === 0 && currentSum === target) {\n // 找到了符合条件的组合\n if (indices.reduce((a, b) => a + b, 0) < minIndexSum) {\n result = indices.slice(); // 拷贝一份下标数组\n minIndexSum = indices.reduce((a, b) => a + b, 0);\n }\n return;\n }\n\n // 从startIndex开始遍历数组,寻找可能的组合\n for (let i = startIndex; i < nums.length; i++) {\n if (currentSum + nums[i] <= target) {\n indices.push(i);\n backtrack(i + 1, count - 1, currentSum + nums[i], indices);\n indices.pop();\n }\n }\n }\n\n // 调用递归函数开始搜索\n backtrack(0, n, sum, []);\n\n return result;\n}\n\n// 测试样例\nconst nums = [3, 2, 4, 5, 7];\nconst n = 3;\nconst target = 10;\nconsole.log(findIndices(nums, n, target)); // 输出 [0, 1, 3]


原文地址: https://www.cveoy.top/t/topic/pHzN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录