2015-10-04 60 views
0

我想做一個遞歸函數,它會打印出所有具有整數數組重複項的排列,但是數字有一個範圍,數組大小的範圍也是如此。假設我們有一個數組num[2],它有從0-1例如一個範圍,它會打印出像如何使用遞歸打印出C中所有數字範圍的排列?

00 
01 
11 
10 

如果它是一個簡單的排列,我可以用一個簡單的置換函數是這樣的:

void permute(int *array,int i,int length) { 
    if (length == i){ 
    printArray(array,length); 
    return; 
    } 
    int j = i; 
    for (j = i; j < length; j++) { 
    swap(array+i,array+j); 
    permute(array,i+1,length); 
    swap(array+i,array+j); 
    } 
    return; 
} 

void swap(char *x, char *y) 
{ 
    char temp; 
    temp = *x; 
    *x = *y; 
    *y = temp; 
} 

但是我怎樣才能使它通過一個數組的範圍與數組給定的大小說n大小?

我的問題是不同的另一個在這裏,因爲我沒有一個數組的值是什麼,示例代碼這樣做,但我需要的是幫助打印範圍n的所有排列的數組ķ點,所以說,n爲3,k爲3,那麼這將是

000 
001 
002 
003 
010 
011 
etc... 
+0

你能共享交換功能嗎? – 2015-10-04 14:42:35

+0

void swap(int * x,int * y) { int temp; temp = * x; * x = * y; * y = temp; } – F22lightning

+0

我無法理解「我」變量。那是什麼 ? – 2015-10-04 15:14:06

回答

0

基於你問什麼,你想與n元素每個陣列與k元素生成的數組,打印所有n^k排列。所以在每個位置i我們必須把數組的每個元素,並繼續爲下一個。像這樣的代碼:

void permute(int *array, int *result, int i, int n, int length) { 
    if (length == i){ 
     printArray(result, length); 
     return; 
    } 

    for (int j = 0; j < n; j++) { 
     result[i] = array[j]; 
     permute(array, result, i + 1, n, length); 
    } 
} 

int main() 
{ 
    int a[] = { 0, 1, 2 }, b[2]; 
    permute(a, b, 0, 3, 2); 
    return 0; 
} 
+0

這似乎在大多數情況下工作,除非有問題,出於某種原因,當嘗試使用4和6有時可以使用,其他時間不使用 – F22lightning

+0

你的意思是不行嗎?有什麼問題? – AKJ88

0

想法是通過每一個可能位級聯到每個長度n-1的排列,以產生長度n的排列。所以,如果你有數字0-2,並要生成長度爲3的排列,首先產生長度爲2的所有排列,然後追加或預先準備的數字01,並且2每個那些:

長度2的置換是:00,01,02,10,11,12,20,21,22

因此,長度3的置換是: 022,100,101,102,110,111,112,120,121,122,200 ...

那麼,如何生成長度爲2的所有排列呢?您生成長度爲1的排列,並將每個數字前置到所有這些排列中。你如何產生長度爲1的排列?沒有長度爲0的排列,因此您只需列出數字。

這裏是僞代碼:

permute(n, digits) { 
    permutations = [] 
    smaller_permutations = permute(n-1, digits) 
    for (i in digits) { 
     if (length(smaller_permutation > 0) { 
      for (j in smaller_permutations) { 
       insert concatenate(i,j) into permutations 
      } 
     } 
     else { 
      insert i into permutations 
     } 
    } 
    return permutations 
}