2017.4.13腾讯实习,软件开发-运营开发岗,2面手撕组合排列C++代码

来源:互联网 发布:nginx内置参数 编辑:程序博客网 时间:2024/06/08 10:09
面试的时候没答出来,回去自己调试出来的源码。

#include #include #include #include using namespace std;//全排列int p_cnt = 0;void Permutation (string pStr, int pBegin){    if (pBegin == pStr.size())    {        p_cnt++;        cout << pStr << endl;    }        else    {        for (int i = pBegin; i < pStr.size(); ++i)        {            char temp = pStr[i];            pStr[i] = pStr[pBegin];            pStr[pBegin] = temp;            Permutation (pStr, pBegin + 1);            temp = pStr[i];            pStr[i] = pStr[pBegin];            pStr[pBegin] = temp;        }    }}//组合int c_cnt = 0;void Combination (string pStr, int m, int n, set s_c){    if (n == 0)    {        c_cnt++;        set::iterator iter;                for (iter = s_c.begin(); iter != s_c.end(); iter++)        {            cout << *iter;        }                cout  << endl;        return;    }        if (m <= 0) { return; }        else    {        Combination (pStr, m - 1, n, s_c);        s_c.insert (pStr[pStr.size() - m]);        Combination (pStr, m - 1, n - 1, s_c);    }}int main (void){    string str = "abcde";    cout << "全排列:" << endl;    Permutation (str, 0);    cout << p_cnt << endl;    set s_c;    cout << "组合:" << endl;    Combination (str, str.size(), 3, s_c);    cout << c_cnt << endl;    system ("pause");    return 0;}
0 0