練習題 -- 排列組合 -- 隊列和遞歸的使用

原文鏈接:https://blog.csdn.net/huangkangying/article/details/6867295

排列和組合算法是考查遞歸的常見算法,這兩種算法能用遞歸簡潔地實現。

本人在經過多次摸索和思考之後,總結如下,以供參考。

程序代碼如下:

#include <stdio.h>
#include <stdlib.h>

char array[] = "abcd";

#define N  4
#define M  3
int queue[N] = {0};
int top = 0;
int flag[N] = {0};

void perm(int s, int n)
{
    int i;

    if (s > n)
    {
        return;
    }

    if (s == n)
    {
        for (i = 0; i < n; i++)
        {
            printf("%c", queue[i]);
        }
        printf("\t");
        return ;
    }

    for (i = 0; i < n; i++)
    {
        if (flag[i] == 0)
        {
            flag[i] = 1;
            queue[s] = array[i]; // 在組合的情況下,依次選擇其中一個存入隊列
            perm(s+1, n);        // 對剩餘的元素再進行排列
            flag[i] = 0;         // 爲下一組排列做準備
        }
    }
}

void comb(int s, int n, int m)
{
    int i;

    if (s > n)
        return ;

    if (top == m)
    {
        for (i = 0; i < m; i++)
        {
            printf("%c", queue[i]);
        }
        printf("\t");
        return ;
    }
    // 組合無順序的問題,不需要和排列標記是否已經訪問
    // 第一種情況:確認首元素參與組合
    queue[top++] = array[s];
    comb(s+1, n, m);
    top--;
    // 第二種情況:去掉首元素後剩餘的進行組合
    comb(s+1, n, m);

}

int main()
{
    printf("\nperm():\n");
    perm(0, N);
    printf("\ncombination():\n");
    comb(0, N, M);
    printf("\n");
    return 0;
}

運行結果

perm():
abcd    abdc    acbd    acdb    adbc    adcb    bacd    badc    bcad    bcda
bdac    bdca    cabd    cadb    cbad    cbda    cdab    cdba    dabc    dacb
dbac    dbca    dcab    dcba
combination():
abc     abd     acd     bcd

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章