基於排列與組合輸出多少中情況詳解

來源:互聯網
上載者:User

排列

複製代碼 代碼如下:#include <stdio.h>
// 主要是找到當前要排的 和後面要排數的關係
int swap(int m,int n)
{
if(n==1)
return m-n+1;
return m*swap(m-1,n-1);

}
int main()
{
int m=5,n=4;
printf("%d",swap(5,4));

}

組合

計算3個A,2個B可以組成多少種排列的問題

思路一:

複製代碼 代碼如下:#include <stdio.h>

/*
3個A,2個B 根據排列 第一個位置
可以是A也可以是B 如A_ _ _ _ 或著 B_ _ _ _ 由於第一個位置
確定了 一個字母 所以 如果確定的是A 則在剩下的四個位置中
就只能有 2個A ,2個B了 所以總的情況就是 A_ _ _ _ +B_ _ _ _ 兩個排列總數之和
*/
int f(int m, int n)
{
if(m==0 || n==0) return 1;
return f(m,n-1)+f(m-1,n);
}

void main ()
{
printf("%d ",f(3,2));
}

思路二:
複製代碼 代碼如下:#include <stdio.h>
#include <math.h>

/*
對於(m+n)!種排列方法是針對所有元素都不重複的情況下計算出的,
如果存在重複,則需要篩選出這些重複的排列情況。
於是我們可以採用捆綁法,將相同的元素綁在一起,由於是組合,所以內部元素的排列問題不予考慮,
這些排列數總共有m!和n!,因此去掉這些重複情況後就得到(m+n)!/(m!*n!)中排法。

m個A n個B的排列一共有(m+n)!/(m!*n!)
而m-1個A n-1個B的排列一共有(m+n-2)!/((m-1)!*(n-1)!)
所以m個A n個B的排列數=m-1個A n-1個B的排列數*(m+n)*(m+n-1)/(m*n)

關鍵是找到(m個A和n個B的排列)和(m-1個A和n-1個B)之間關係

*/
int f(int m, int n)
{
if(m==0 || n==0) return 1;
return f(m-1,n-1)*(m+n-1)*(m+n)/m/n;
}

void main ()
{
printf("%d ",f(3,2));
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.