算法复习——排列|组合|指数枚举

递归实现指数型枚举

从 1 到 n这 n 个整数中随机选取任意多个,输出所有可能的选法,一共有多少种选择方式?

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

const int N=20;

int a[N];
bool st[N];
int ans;
int n;

void dfs(int x)
{
    if(x>n)
    {
        for(int i=1;i<=n;i++)
            if(st[i]) cout<<i<<" ";
        cout<<endl;
        ans++;
        return ;
    }
    st[x]=true;
    dfs(x+1);
    st[x]=false;
    
    st[x]=false;
    dfs(x+1);
    st[x]=true;
}

int main()
{
    cin>>n;
    dfs(1);
    cout<<"一共有"<<ans<<"种组合方式"<<endl;
    
    return 0;
}

总结:每一个数,有选和不选,两种可能,所以一共有2n种选法,即组合方式有2n种

递归实现排列型枚举

从1~n选n个数,排列后按顺序打乱,一共有多少种排列方法,怎么排列的?

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

const int N=10;

bool st[N];
int a[N];

int n;

void dfs(int x)
{
    if(x>n)
    {
        for(int i=1;i<=n;i++)
            cout<<a[i]<<" ";
        cout<<endl;
        return ;
    }
    for(int i=1;i<=n;i++)
    {
        if(!st[i])
        {
            a[x]=i;
            st[i]=true;
            dfs(x+1);
            st[i]=false;
        }
    }
}

int main()
{
    cin>>n;
    dfs(1);
    return 0;
}

总结:使用布尔数组标记,是否被访问过,被访问过,就找另外的;一共有n!种组合方式,n个中选n个。

递归实现组合型枚举

从 1∼𝑛 这 n 个整数中随机选出 m 个,输出所有可能的选择方案;一共有多少个方案?

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

const int N=30;

int n,m;
bool st[N];

void dfs(int start,int x)//从那个数开始选,选择了多少个数了
{
    if(x>m)
    {
        for(int i=1;i<=n;i++)
            if(st[i]) cout<<i<<" ";
        cout<<endl;
        return ;
    }
    for(int i=start;i<=n;i++)
    {
        if(!st[i])
        {
            st[i]=true;
            dfs(i+1,x+1);
            st[i]=false;
        }
    }
}

int main()
{
    cin>>n>>m;
    dfs(1,1);
    return 0;
}

总结:我们需要记录从谁开始选,然后选它后面的m个,选过的就不选了,没有选的话就选它。如果可以选够m个就输出。

通过公式可以计算方案数

相关推荐
mit6.82428 分钟前
固定中间
算法
老马啸西风36 分钟前
成熟企业级技术平台 MVE-010-跳板机 / 堡垒机(Jump Server / Bastion Host)
人工智能·深度学习·算法·职场和发展
立志成为大牛的小牛1 小时前
数据结构——五十九、冒泡排序(王道408)
数据结构·学习·程序人生·考研·算法
s09071361 小时前
下视多波束声呐进行测绘作业注意事项
算法·海洋测绘·下视多波束
papership1 小时前
【入门级-数据结构-3、特殊树:完全二叉树的定义与基本性质】
数据结构·算法
中國龍在廣州1 小时前
AI顶会ICML允许AI参与审稿
人工智能·深度学习·算法·机器学习·chatgpt
立志成为大牛的小牛1 小时前
数据结构——六十、快速排序(王道408)
数据结构·程序人生·考研·算法·排序算法
Dev7z1 小时前
基于MATLAB的GA–PSO混合算法无线传感器网络节点部署优化研究
网络·算法·matlab
koo3642 小时前
12.14周报
人工智能·算法