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

递归实现指数型枚举

从 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个就输出。

通过公式可以计算方案数

相关推荐
小羊在奋斗5 分钟前
【算法】动态规划:回文子串问题、两个数组的dp
算法·动态规划
编程在手天下我有31 分钟前
机器学习中的 K-均值聚类算法及其优缺点
算法·均值算法
喜欢理工科1 小时前
18 C语言标准头文件
c语言·python·算法·c语言标准头文件
a13096023361 小时前
编译原理 pl0 词法解析器 使用状态机与状态矩阵,和查找上一步得到分析
线性代数·算法·矩阵
爱笑的Sunday1 小时前
【LeetCode 题解】算法:15.三数之和
java·数据结构·算法·leetcode
John Art2 小时前
PAT甲级(Advanced Level) Practice 1028 List Sorting
算法
花鱼白羊2 小时前
代码随想录刷题day52|(二叉树篇)106.从中序与后序遍历序列构造二叉树(▲
算法
ゞ 正在缓冲99%…2 小时前
leetcode3.无重复字符的最长字串
算法·leetcode·滑动窗口
一只_程序媛2 小时前
【leetcode hot 100 739】每日温度
算法·leetcode·职场和发展
我想吃余2 小时前
【初探数据结构】二叉树的顺序结构——堆的实现详解(上下调整算法的时间复杂度分析)
数据结构·算法