zoukankan      html  css  js  c++  java
  • 【递归】n个数的集合的所有子集, 去掉重复的项

    输入:

    3

    1 1 3

    输出:

    1

    1 1

    1 1 3

    1 3

    3

    Delphi代码:

    unit unrepeat_combination;

    const
    max_n = 10;

    var
    n, m: integer;
    rcd, num, used: array[0..max_n] of integer;

    procedure unrepeat_combination(index, p: integer);
    var
    i: integer;
    begin
    if index > 0 then
    begin
    for i := 0 to index - 2 do
    Write(rcd[i], ' ');
    writeln(rcd[index - 1]);
    end;

    for i := p to m - 1 do //共m个不同的数
    if used[i] > 0 then
    begin
    Dec(used[i]);
    rcd[index] := num[i];
    unrepeat_combination(index + 1, i); //因为used[i]可能大于0, 所以这里不能用 i+1
    Inc(used[i]);
    end;
    end;

    var
    i, j, val: integer;
    begin
    while not seekeof do
    begin
    readln(n);
    m := 0;
    for i := 0 to n - 1 do
    begin
    Read(val);
    j := 0;
    while j < m do
    begin
    if val = num[j] then
    begin
    Inc(used[j]);
    break;
    end;
    Inc(j);
    end;
    if j = m then
    begin
    used[m] := 1;
    num[m] := val;
    Inc(m);
    end;
    end;
    unrepeat_combination(0, 0);
    end;
    end.

    C++代码:

    #include <stdio.h>
    #define MAX_N 10

    int rcl[MAX_N], num[MAX_N], used[MAX_N];
    int m,n;

    void unrepeat_combination(int index, int p)
    {
    int i;
    for (i=0; i<index; i++)
    {
    printf("%d", rcl[i]);
    if (i<index-1)
    {
    printf(" ");
    }
    else
    printf("\n");
    }

    for (i=p; i<n; i++)
    {

    if (used[i]>0)
    {
    used[i]--;
    rcl[index] = num[i];
    unrepeat_combination(index+1, i);
    used[i]++;
    }
    }
    }

    int read_data()
    {
    if (scanf("%d", &n)== EOF)
    {
    return 0;
    }
    int i, j, val;
    m = 0;
    for (i=0; i<n; i++)
    {
    scanf("%d", &val);
    for (j=0; j<m; j++)
    {
    if (val == num[j])
    {
    used[j]++;
    break;
    }
    }
    if (j==m)
    {
    num[m] = val;
    used[m] = 1;
    m++;
    }
    }
    return 1;
    }

    void main()
    {
    while(read_data())
    {
    unrepeat_combination(0, 0);
    }
    }




  • 相关阅读:
    django http请求request详解
    HTTP协议向服务器传参
    股票交易费用及复利计算公式
    scrapy初步使用
    通过 multiprocessing Pool 线程池加速爬虫的处理
    通过 PIL 和 Python-tesseract 模拟登陆
    BeautifulSoup
    xpath
    http 请求特殊字符
    HTTP cookies
  • 原文地址:https://www.cnblogs.com/wouldguan/p/2435232.html
Copyright © 2011-2022 走看看