这个dfs怎么优化捏?蒟蒻求助
查看原帖
这个dfs怎么优化捏?蒟蒻求助
843596
Otion楼主2023/1/8 16:09

变量含义有注释哦

#include <iostream>
using namespace std;
int total_num;
int demand;
int ways;
// total_num是题干要求分解的数
// demand是需要分成几个数
//ways是方案数量
void dfs(int total, int count, int mark)
//函数里面total是还有多少没有被分
//count是数现在分出来几个数了
//为了避免重复,就从小到大分组了,1 2 5这种
//所以做了个mark记录上一次搜索分出来的数,确保之后的数不会小于他
{
    int sum = total_num - total;
    if (demand - count > total)
    {
        return;
    }
    if (total == 0 && count == demand)
    {
        ways++;
        return;
    }
    for (int i = mark; i <= total; i++)
    {

        count++;
        dfs(total - i, count, i);
        count--;
    }
}
int main()
{
    cin >> total_num >> demand;
    dfs(total_num, 0, 1);
    cout << ways << endl;
    return 0;
}
2023/1/8 16:09
加载中...