天天看點

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

繼續閱讀