如何优雅实现数组中所有5元素组合的乘积求和?
Hey there! I get you—five nested loops are definitely a pain, both to write and to run, especially if your array grows larger. Let's fix this with a smarter approach that's way more efficient and elegant.
问题本质:初等对称和
What you're actually calculating here is the 5th elementary symmetric sum of the array. The k-th elementary symmetric sum of a set of numbers is the sum of all products of k distinct elements from the set. That's exactly what your nested loops are doing, just in a very brute-force way.
动态规划解法(O(nk)时间复杂度)
We can compute this using dynamic programming, which cuts the time complexity from O(n⁵) (your original approach) to O(n*k) where k=5—this is night-and-day faster for larger arrays.
Here's the core idea:
- We maintain an array
dpwheredp[m]stores the m-th elementary symmetric sum up to the current element we've processed. - Start with
dp[0] = 1(the empty product, which is the identity for multiplication) and all otherdp[m] = 0. - For each number in the array, update the
dparray from back to front (to avoid reusing the same element multiple times in a single product). For each m from k down to 1,dp[m] = dp[m] + dp[m-1] * currentNumber. This adds all new products that include the current number (by multiplying it with every possible (m-1)-element product we already have).
代码实现
function getSum(arr) { const targetCount = 5; // dp[m] will hold the m-th elementary symmetric sum const dp = new Array(targetCount + 1).fill(0); dp[0] = 1; // Base case: empty product is 1 for (const num of arr) { // Update from back to front to prevent reusing the same element multiple times for (let m = targetCount; m >= 1; m--) { dp[m] += dp[m - 1] * num; } } return dp[targetCount]; } // Test with your array const arr = [2, 3, 4, 12, 4, 55, 8, 16]; console.log(getSum(arr)); // This will match your nested loop result exactly
为什么这比嵌套循环好?
- Efficiency: For an array of length 20, your nested loop would run 15504 times (C(20,5)), while this approach runs just 20*5=100 iterations. For larger arrays, the gap becomes enormous.
- Flexibility: Want to calculate the sum of products of 3 elements instead? Just change
targetCountto 3—no need to rewrite layers of loops. - Readability: The code is concise and clearly expresses the intent, unlike nested loops which are hard to parse at a glance.
内容的提问来源于stack exchange,提问作者Vic

