[演算法]組合類問題

orchid發表於2014-10-15

1,組合相關公式

C(n,m)=n*(n-1)*(n-2)...*(n-m-1)/m!=n!/(m!*(n-m)!)

C(n,m)=C(n,n-m)

C(n+1,m)=C(n,m)+C(n,m-1)

C(n,1)+C(n,2)+…+C(n,n)=2^n;

 

2,相關演算法

Question 1: 輸入一個字串,列印出該字串中字元的所有組合。

演算法1:同樣可以按照文章http://www.cnblogs.com/orchid/p/4025172.html中提到的思路,有長度為strlen(s)個盒子,每個盒子裡面有0和1,總共有幾種不同的排列方法?

void Combination::GetCombination(int* holders,int end)
{
    for(int i=0;i<2;i++)
    {
        holders[end]=i;
        if(end==strlen(elements)-1)   //elements是const char*型別,
        {
            print(holders);
        }
        else{
            GetCombination(holders,end+1);
        }
    }
}

演算法2,不用遞迴,直接迴圈。

void Combination::PrintAllCombination2()
{
    vector<string> holder;
    holder.push_back("");

    for(int i=0;i<strlen(elements);i++)
    {
        int lastOne=holder.size();
        for(int j=0;j<lastOne;j++)
        {
            string temp=holder.at(j)+elements[i];
            holder.push_back(temp);
            cout << temp << ",";
        }
    }
}

假設一次迴圈之後vector裡面的元素是,"" "a" "b" "ab",那麼下次迴圈需要將第三個字元c加入序列中,即在vector中插入"c","ac","bc","abc" --- 字元c與vector中現有子串的和。

 

相關文章