Permutation_Subset

Please indicate the source if you want to reprint: http://blog.csdn.net/gaoxiangnumber1.
Permutation
设R = {r1, r2, … , rn}是要进行排列的n个元素, Ri = R-{ri}; 集合X中元素的全排列记为 Permutation(X), (ri)Permutation(X)表示在全排列Permutation(X)的每一个排列前加上前缀ri得到的排列.
R的全排列可归纳定义如下:
当n=1时,Permutation(R)={r},r是集合R中唯一的元素;
当n>1时,Permutation(R)由(r1)Permutation(R1), (r2)Permutation(R2), …, (rn)Permutation(Rn)构成。
N个元素的全排列共N!个。第1个元素由N个位置可以选择;2:N-1;3:N-2…,所以共N!.
算法Permutation(array, first, last)递归地产生所有前缀是array[0:first-1],且后缀是array[first:last]的所有排列.函数调用(array, 0, length-1)则产生array的全排列.
Subset
N个元素的全部子集共2N个。每个元素有两种选择:在/不在该子集。通过一个bool数组来辅助判断每个元素是否在当前的子集中。
Codes:

#include<iostream>
using namespace std;

bool exist[100];

void Permutation(int test[], int first, int last);
void PrintSubset(int test[], bool exist[], int last);
void Subset(int test[], bool exist[], int first, int last);

int main()
{
    int test[] = {1, 2, 3, 4};
    cout << "Permutation:\n";
    Permutation(test, 0, 3);
    cout << "Subset:\n";
    Subset(test, exist, 0, 3);

    return 0;
}

void Permutation(int test[], int first, int last)  // get the permutation of test[first, last]
{
    if(first == last)  // no need to swap element, so we get one permutation
    {
        for(int index = 0; index <= last; index++)
        {
            cout << test[index] << " ";
        }
        cout << endl;
    }
    else
    {
        for(int index = first; index <= last; index++)
        {
            swap(test[first], test[index]);  // exchange the first element with all elements one by one
            Permutation(test, first + 1, last);  // get the permutation of test[first + 1, last]
            swap(test[first], test[index]);  // recover the exchange
        }
    }
}

void Subset(int test[], bool exist[], int first, int last)  // get the subset of test[first, last]
{
    if(first == last)  // reach the end
    {
        exist[first] = true;  // the last element is in this subset
        PrintSubset(test, exist, last);  // get one subset
        exist[first] = false;
        PrintSubset(test, exist, last);
        return;
    }
    exist[first] = true;  // the first element is in this subset
    Subset(test, exist, first + 1, last);  // get the subset of test[first + 1, last]
    exist[first] = false;
    Subset(test, exist, first + 1, last);
}

void PrintSubset(int test[], bool exist[], int last)
{
    for(int index = 0; index <= last; index++)
    {
        if(exist[index])  // if  current element is in the subset, print it.
        {
            cout << test[index] << " ";
        }
    }
    cout << endl;
}

Please indicate the source if you want to reprint: http://blog.csdn.net/gaoxiangnumber1.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值