當涉足算法領域,排列組合應該是最基礎的。最近遇到了,作個記錄,小白看看,大神繞路
一、補充公式
排列的定義:從n個不同元素中,任取m(m≤n,m與n均爲自然數,下同)個元素按照一定的順序排成一列,叫做從n個不同元素中取出m個元素的一個排列;從n個不同元素中取出m(m≤n)個元素的所有排列的個數,叫做從n個不同元素中取出m個元素的排列數,用符號 A(n,m)表示,公式如下:
A(n,m) = n!/(n-m)!
組合的定義:從n個不同元素中,任取m(m≤n)個元素併成一組,叫做從n個不同元素中取出m個元素的一個組合;從n個不同元素中取出m(m≤n)個元素的所有組合的個數,叫做從n個不同元素中取出m個元素的組合數。用符號 C(n,m) 表示:
C(n,m) = n!/(m!*(n-m)!) (n>=m)
二、代碼實現
2.1 c++代碼實現排列
話不多說,直接上代碼:
#include <iostream>
using namespace std;
//交換函數
void swap(int& a, int& b )
{
int temp = a;
a = b;
b = temp;
}
/*入參:
begin 要排列的起始位置
end 要排列的結束位置
a[] 要排列的數組
*/
void permutate(int begin, int end, int a[])
{
if(begin == end)//已經到了最後一個位置,進行輸出
{
for(int i=0; i < end;i++)
{
cout<<a[i];
}
cout<<endl;
}
for(int i= begin; i < end; i++)
{
swap(a[begin],a[i]);
permutate(begin + 1,end,a);//遞歸下一個位置
swap(a[i],a[begin]);//回溯
}
}
int main()
{
int a[5] = {1,2,3,4,5};
permutate(0,3,a);//對數組中前三個數進行排列
return 0;
}
輸出爲:
123
132
213
231
321
312
當然也可進行簡單的優化:
template<class T,int N>
void permutate(int begin, int end, T (&a)[N])
{
if(0 > begin || begin > end || end > N)
{
cout<<"輸入參數錯誤"<<endl;
return;
}
//輸出情況
if(begin == end)
{
for(int i=0; i < end;i++)
{
cout<<a[i];
}
cout<<endl;
}
for(int i= begin; i < end; i++)
{
swap(a[begin],a[i]);
permutate(begin + 1,end,a);
swap(a[i],a[begin]);
}
}
2.2 c++代碼實現組合
代碼:
#include <iostream>
using namespace std;
void combinate(int iPos, int iProc, int iTol, int iKey, int data[],int des[])
{
if(iProc > iTol)
{
return;
}
if(iPos == iKey)
{
for(int i = 0;i < iKey; i++)
{
cout<<des[i]<<" ";
}
cout<<endl;
return;
}
else
{
combinate(iPos,iProc+1,iTol,iKey,data,des);
des[iPos] = data[iProc];
combinate(iPos+1,iProc+1,iTol,iKey,data,des);
}
}
int main()
{
int a[6] = {1,2,3,4,5,6}, b[5];
combinate(0, 0, 5, 3 , a,b);
//如果需要終端輸入
/*
cin>>n>>k;
if(n > k > 0)
{
int data[n],temp[n];
for(i = 0; i < n; i++ )
{
data[i] = i+1;
}
combinate(0, 0, n, k, data, temp);
}
*/
return 0;
}
輸出爲:
3 4 5
2 4 5
2 3 5
2 3 4
1 4 5
1 3 5
1 3 4
1 2 5
1 2 4
1 2 3
平時工作一般用不到這些,最近自己琢磨發現雖然邏輯簡單,但是寫起來還確實不知道怎麼下手。。。
所以不能羨慕算法大神年薪幾十萬上百萬,畢竟得腦子好用不是?
===============
想分一杯羹,還是儘早學習,共勉!