用遞迴實現排列組合

來源:互聯網
上載者:User

 

用遞迴實現排列

“遞迴回溯”在排列中的主要思想

P(N,M)就相當於在一個M * N的棋盤上每行放一個棋子,且保證每列只有一個棋子.
每一枚棋子都有N個位置可放, 因此就可以窮舉每一個棋子的位置, 從第一行開始放,如果所放的列沒放過棋子則從下一行的起始位置開始放, 否則放下一列, 如果已經沒有位置可以放了, 則回溯(回退一行)...如果放下了M枚棋子,則所在的每枚棋子所在的列構成的序列即是一個滿足要求的排列...

 

#include<stdio.h>
#include<string.h>

#define N 5
#define M 3

int used[N], count, b[M];
//used記錄某個數是否被使用過,count記錄解的個數,b記錄每次所得的解
void search( int );

int main()
{
memset( used, 0, N * sizeof( used[0] ) );
search( 0 );
printf( "%d/n", count );
return 0;
}
void search( int depth )
{
int i;
if( depth == M )  //找到滿足條件的解,則輸出
{
for( i = 0; i < M; i++ )
printf( "%d ", b[i] );
printf( "/n" );
count++;
return;
}
for( i = 0; i < N; i++ )
{
b[depth] = i + 1;
if( !used[i] )  //檢測是否被使用過
{
used[i] = 1; 
search( depth + 1 );
used[i] = 0;
}
}
}

depth是數組b的下標:取了數就加1, 否則就不變...

 

用遞迴實現組合:

“遞迴中分而治之的思想”在排列中的應用

從n個數取m個數的組合數,相當於就是用公式C(n,m) = C(n-1,m) + C(n-1,m-1)。

 

#include<stdio.h>

#define N 5
#define M 3

void search( int, int, int );
int b[M], count;//數組b記錄每次產生的解,count記錄解的個數
int main()
{
count = 0;
search( 0, N, M );
printf( "%d/n", count );
return 0;
}
void search( int depth, int n, int m )
{
int i;
if( m == 0 ) //滿足條件則輸出
{
for( i = 0; i < M; i++ )
printf( "%d ", b[i] );
printf( "/n" );
count++;
return ;
}
if( m > n || n <= 0 ) return; //依常識剪枝
b[depth] = n;
search( depth + 1, n - 1, m - 1 );
b[depth] = 0;
search( depth, n - 1, m );
}

 

聯繫我們

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