組合問題及代碼實現,組合問題代碼實現

來源:互聯網
上載者:User

組合問題及代碼實現,組合問題代碼實現

組合問題遞迴實現

以在n個數中選取m(0<m<=n)個數為例,問題可分解為:

1. 首先從n個數中選取編號最大的數,然後在剩下的n-1個數裡面選取m-1個數,直到從n-(m-1)個數中選取1個數為止。
2. 從n個數中選取編號次小的一個數,繼續執行1步,直到當前可選編號最大的數為m。

很明顯,上述方法是一個遞迴的過程,也就是說用遞迴的方法可以很乾淨利索地求得所有組合。

下面是遞迴方法的實現:
(1)求從數組a[1..n]中任選m個元素的所有組合。
(2)a[1..n]表示候選集,n為候選集大小,n>=m>0。
(3)b[1..M]用來儲存當前組合中的元素(這裡儲存的是元素下標),
(4)常量M表示滿足條件的一個組合中元素的個數,M=m,這兩個參數僅用來輸出結果。

代碼實現:

  1. #include <iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. void combine( int a[], int n, int m,  int b[], const int M )  
  6. {  
  7.     for(int i=n; i>=m; i--)   // 注意這裡的迴圈範圍  
  8.     {  
  9.         b[m-1] = i - 1;  
  10.         if (m > 1)  
  11.             combine(a,i-1,m-1,b,M);  
  12.         else                     // m == 1, 輸出一個組合  
  13.         {  
  14.             for(int j=M-1; j>=0; j--)  
  15.                 cout << a[b[j]] << " ";  
  16.             cout << endl;  
  17.         }  
  18.     }  
  19. }  
  20.   
  21. int main()  
  22. {  
  23.     const int N = 4;  
  24.     int a[N];  
  25.     for(int i=0; i<N; i++)  
  26.         a[i] = i+1;  
  27.     for(int M=1; M <= 4; M++)  
  28.     {  
  29.         //遞迴方法  
  30.         int b[M];  
  31.         combine(a,N,M,b,M);  
  32.     }  
  33.     return 0;  
  34. }  
運行結果






問個對於JAVA排列組合代碼的問題

package test;
public class tt {

/**
* @param args
*/
public static void main(String[] args) {
String[] arr={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"
,"0","1","2","3","4","5","6","7","8","9"};
int h=0;
for(int i=0;i<arr.length;i++)
{
for(int j=0;j<arr.length;j++)
{
for(int k=0;k<arr.length;k++)
{
System.out.print(arr[i]+arr[j]+arr[k]+" ");
h++;
}
System.out.println();
}
}
}

}
unicode編碼我忘記了,就直接手寫上去了,方正是實現了。呵呵
 
對於複式排列組合代碼問題!!

沒有人能解決。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.