数组中元素的组合 [英] Combinations of elements in an array

查看:99
本文介绍了数组中元素的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个C程序来查找给定数组和指定长度的所有组合。

I'm trying to write a C program to find all the combinations of an given array and a specified length. This is what I've done so far..

#include <stdio.h>

void com(int* a, int* t, int len, int i) {

    int j, k;

    if(len == 0) {

        for(k=0;k<3;k++) {
            printf("%d  ",t[k]);
        }

        printf("\n");
        return;
    }

    for(j = i ; j <= 4-len ; j++) {  // 4 = original array size 
        t[3-len] = a[j];
        com(a,t,len-1,i+1);
    }
}

main() {

    int t[3];
    com((int[]){4,1,3,2},&t[0],3,0); // 3 = combination length
}

此代码中的问题是它没有选择跳过重复项,组合重复项。例如,它为数组{1,2,3,4}生成

The problem in this code is that it has no option to skip duplicates, repetitions of combination. e.g for the array {1,2,3,4} it generates

1  2  3  
1  2  4  
1  3  3  
1  3  4  
2  2  3  
2  2  4  
2  3  3  
2  3  4 

,但应该会生成

1 2 3
1 2 4
1 3 4
2 3 4

我该怎么办?我不确定该怎么做。任何帮助将不胜感激。谢谢。

What can I do for that? I'm not sure how to do that. Any kind of help would be appreciated. Thanks.

此外,如果有替代方案和更好的优化解决方案,请随时分享。

Also, if there is an alternative and better optimized solution than this, feel free to share.

推荐答案

要修复的示例

void com(int *a, int *t, int len, int i){
    if(i == len){
        for(int k = 0; k < len; k++)
            printf("%d ", t[k]);
        printf("\n");
        return;
    }
    while(*a){
        t[i] = *a;
        com(++a, t, len, i+1);
    }
}

int main(void){
    int t[3];

    com((int[]){1,2,3,4, 0}, t, 3, 0);
    //                   ^end mark
    return 0;
}

这篇关于数组中元素的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆