Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何将数组中的4个整数相加为整数n,最有效的方法是什么?_Arrays - Fatal编程技术网

Arrays 如何将数组中的4个整数相加为整数n,最有效的方法是什么?

Arrays 如何将数组中的4个整数相加为整数n,最有效的方法是什么?,arrays,Arrays,我有一个由m个整数组成的数组,我想检查数组中是否有4个整数(允许重复)和给定的整数n 例如,如果有一个数组[8,4,2,1],且n=8,则可能的组合为-{2,2,2},{4,2,1,1} 目前,我使用4 for循环进行计数,如下所示: int ans = 0; for(int a = 0; a<arr.size(); a++) { for(int b = 0; b<arr.size(); b++) { for(int c = 0; c<arr.size

我有一个由m个整数组成的数组,我想检查数组中是否有4个整数(允许重复)和给定的整数n

例如,如果有一个数组[8,4,2,1],且n=8,则可能的组合为-{2,2,2},{4,2,1,1}

目前,我使用4 for循环进行计数,如下所示:

int ans = 0;

for(int a = 0; a<arr.size(); a++) {
    for(int b = 0; b<arr.size(); b++) {
        for(int c = 0; c<arr.size(); c++) {
            for(int d = 0; d<arr.size(); d++) {
                if(arr[a] + arr[b] + arr[c] + arr[d] == n) ans++;
            }
        }
    }
}

printf("%d", ans);
intans=0;
对于(int a=0;a
  • 对输入数组进行排序
    X
    删除重复项
  • 惰性地产生变体,从最大的
    C[0]^4
    ,到最小的
    C[3]^4
    ,删除部分乘积P{C[i]}超过目标
    X
    的组合集
  • 当第一个元素升到四次方
    C[0]^4
    小于
    X
  • 利润
  • 通常,编程语言会提供上述算法的部分或全部支持。例如,在python中,您可以使用
    itertools
    构建块惰性地列出数组的所有排列,因此只需对修剪逻辑进行编码:

    from itertools import combinations_with_replacement as cwr
    
    N = 4 # number of elements in the combination
    X = [2, 3, 1, 5, 4, 3] # input array
    
    for P in cwr(sorted(set(X), reverse=True), 4):
        print(P) // put checking logic instead of print
    

    看起来像一个修改过的蛮力。时间复杂度是多少?是关于阶乘(数组大小)?@user3243499-我将其归类为,所以最坏的情况-是的,阶乘