编程语言
首页 > 编程语言> > Problem P30. [算法课分支限界法]组合

Problem P30. [算法课分支限界法]组合

作者:互联网

分支树的思想遍历所有可能性,然后加上限制条件,剪枝掉不符合条件的分支,比如只能选出k个数进行组合,那么curk==k时结束这个分支,还有就是注意边界的问题,curn>n

#include<iostream>
#include<bits/stdc++.h>
#include<cstdio>
#include<string>

using namespace std;

vector<string> strs;

int n=0, k=0;

template<typename T> string toString(const T& t){
    ostringstream oss;  //创建一个格式化输出流
    oss<<t;             //把值传递如流中
    return oss.str();
}

void bfs(int curk, int curn, string curstr){
    if (curk==k){
        strs.push_back(curstr);
        return;
    }
    if (curn>n){
        return;
    }
    if (curk>0){
        bfs(curk+1, curn+1, curstr+" "+toString(curn));
    }else {
        bfs(curk+1, curn+1, curstr+toString(curn));
    }
    bfs(curk, curn+1, curstr);
}

int main()
{
    cin >> n >> k;
    bfs(0, 1, "");
    for (int i = 0; i < strs.size(); i++){
        cout << strs[i] << "\n";
    }
    return 0;
}

标签:int,curk,bfs,curstr,curn,Problem,include,P30,限界
来源: https://www.cnblogs.com/understanding-friends/p/16699901.html