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

面试的时候没答出来,回去自己调试出来的源码。

#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;
}

你可能感兴趣的:(C++)