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

递归实现指数型枚举

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

通过公式可以计算方案数

相关推荐
用户979984807181 小时前
200 行代码写一个能跑的 AI Agent:不依赖任何框架,只靠 tool-calling 原理
算法
threerocks1 小时前
【Muse实战】X 流量作战室搭建保姆级教程 - 拥有你自己的运营团队
算法
GreenTea1 小时前
深度拆解 ScienceBuddy:如何用“双层递归自进化”构建高可靠科研 Agent Harness
前端·后端·算法
花椒技术1 小时前
2.46 秒生成 5 秒视频:拆解 H3 Max 的模型、推理栈与硬件协同
算法·音视频开发·视频编码
vivo互联网技术1 小时前
ART:妆容迁移框架,重新定义高保真妆容迁移 | ECCV 2026
人工智能·算法·图像识别
用户0441440924492 小时前
卫星信号模拟器里的四个坐标转换公式
算法
橘和柠2 小时前
阿里 open-code-review (AI代码审查工具)实战:安装、四层规则链、自定义规则格式与实测避坑
算法·面试
得物技术2 小时前
别再只卷向量检索了,得物交易搜索如何用“生成式”实现召回范式跃迁?
人工智能·算法·llm
罗西的思考2 小时前
[Agent Memory / 强化学习] MemPO源码学习笔记 ---(4)--- Rollout实现细节
人工智能·算法
罗西的思考2 小时前
机器人 / 物理 Agent Harness 综合分析与对比:从「更强的模型」到「更好的系统」
人工智能·算法·机器学习