n個元素的全排列演算法

來源:互聯網
上載者:User
 

/*
 * 輸出n個元素的全排列
 */

#include <stdio.h>

void arrange(char *s, int k, int m);
void swap(char *s1, char *s2);

int main(void)
{
    int n;
    int i;
    char *set;
    
    printf("Please input the number of elements (>=0): ");
    scanf("%d", &n);
    if (n <= 0) {
        printf("WARN! The number should be >= 1!/n");
        exit(0);
    }
    
    set = (char *)calloc(n, sizeof(char)); /* 分配存放集合元素的空間 */
    if (!set) {
        printf("Sorry! Not enough memory!/n");
        exit(0);
    }

    /* 讀取字元元素 , 限制了輸入格式 */
    printf("Please input the elements ('X X X ...'):/n/t");
    for (i = 0; i < n; i++)
    /* Notice the '%ls' : get the next non-blank character */
        scanf("%ls", &set[i]);
        
    printf("The set is: {");
    for (i = 0; i < n - 1; i++)
        printf("%c, ", set[i]);
    printf("%c}/n", set[i]);
    
    printf("All arragnement is as follows:/n");
    arrange(set, 0, n-1);
    
    free(set);
    
    getchar(); /* 防止輸出視窗一閃關閉 */
    getchar();
    
    return 0;
}

void arrange(char *s, int k, int m)
{
    int i;
    
    if (k == m) {
        printf("/t");
        for (i = 0; i <= m; i++)
             printf("%c", s[i]);
        printf("/n");
    } else {
        for (i = k; i <= m; i++) {
            swap(&s[k], &s[i]);
            arrange(s, k + 1, m);
            swap(&s[k], &s[i]);
        }
    }
}

void swap(char *s1, char *s2)
{
    char temp = *s1;
    *s1 = *s2;
    *s2 = temp;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.