多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 找到四个总和为给定值的元素| 集合 1(n ^ 3 解) > 原文: [https://www.geeksforgeeks.org/find-four-numbers-with-sum-equal-to-given-sum/](https://www.geeksforgeeks.org/find-four-numbers-with-sum-equal-to-given-sum/) 给定一个整数数组,请找到该数组中四个和的总和等于给定值 X 的所有组合。 例如,如果给定的数组为{10,2,3,4,5, 9、7、8}且 X = 23,则您的函数应打印“ 3 5 7 8”(3 + 5 + 7 + 8 = 23)。 **朴素的解决方案**将生成所有可能的四元组,并将每个四元组的和与 X 进行比较。以下代码使用四个嵌套循环 实现了此简单方法 ## C++ ```cpp // C++ program for naive solution to // print all combination of 4 elements // in A[] with sum equal to X  #include <bits/stdc++.h> using namespace std; /* A naive solution to print all combination  of 4 elements in A[]with sum equal to X */ void findFourElements(int A[], int n, int X) { // Fix the first element and find other three for (int i = 0; i < n - 3; i++) {     // Fix the second element and find other two     for (int j = i + 1; j < n - 2; j++)     {         // Fix the third element and find the fourth         for (int k = j + 1; k < n - 1; k++)         {             // find the fourth             for (int l = k + 1; l < n; l++)             if (A[i] + A[j] + A[k] + A[l] == X)                 cout << A[i] <<", " << A[j]                       << ", " << A[k] << ", " << A[l];         }      } } } // Driver Code int main() {     int A[] = {10, 20, 30, 40, 1, 2};     int n = sizeof(A) / sizeof(A[0]);     int X = 91;     findFourElements (A, n, X);     return 0; } // This code is contributed // by Akanksha Rai ```