在数组中找到和为目标值的 n 个整数的下标(JavaScript)
"在数组中找到和为目标值的 n 个整数的下标(JavaScript)"\n\n本篇文章介绍了如何使用 JavaScript 编写函数,在给定数组中找到和为目标值的 n 个整数的下标,并返回下标和最小的组合。\n\n问题描述\n\n给定一个整数数组 ( 数组长度大于等于 5) nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那 n ( n<nums.length) 个整数,并返回它们的数组 ( 如果有多个下标组合都满足,则返回下标和最小的哪一组) 的下标。\n\n注意:数组中同一个元素在答案里不能重复出现。\n\n例如:\n\n输入:nums = [3, 2, 4, 5, 7], n=3,target = 10\n输出: [0, 1, 3]\n\nJavaScript 代码:\n\njavascript\nfunction findIndices(nums, n, target) {\n const combinations = getCombinations(nums, n);\n let smallestSum = Infinity;\n let smallestIndices = [];\n \n for (let indices of combinations) {\n let sum = 0;\n for (let index of indices) {\n sum += nums[index];\n }\n \n if (sum === target && indices.join('') < smallestIndices.join('')) {\n smallestSum = sum;\n smallestIndices = indices;\n }\n }\n \n return smallestIndices;\n}\n\nfunction getCombinations(nums, n) {\n const combinations = [];\n backtrack([], 0);\n return combinations;\n \n function backtrack(indices, start) {\n if (indices.length === n) {\n combinations.push(indices);\n return;\n }\n \n for (let i = start; i < nums.length; i++) {\n backtrack(indices.concat(i), i + 1);\n }\n }\n}\n\n\n用法示例:\n\njavascript\nconst nums = [3, 2, 4, 5, 7];\nconst n = 3;\nconst target = 10;\n\nconsole.log(findIndices(nums, n, target)); // [0, 1, 3]\n\n\n代码解释:\n\n该函数首先使用 getCombinations 函数获取给定数组中长度为 n 的所有组合的下标。然后,它遍历这些组合,并计算它们的和。如果和等于目标值 target,并且当前组合的下标比之前找到的组合的下标更小,则更新最小下标和最小和。最后,返回最小下标。\n\n总结\n\n本篇文章介绍了如何使用 JavaScript 编写函数来解决在数组中找到和为目标值的 n 个整数的下标的问题,并提供了详细的代码解释和示例。\n
原文地址: https://www.cveoy.top/t/topic/pHsN 著作权归作者所有。请勿转载和采集!