二维数组的全排列

https://lwz777.iteye.com/blog/749828

 /**
  *
  * 使用递归调用将二维数组中的值进行排列组合
  *
  * @param doubleArrays
  * @return
  */
 private static String[][] doExchange(String[][] doubleArrays) {
	  int len = doubleArrays.length;
	  if (len >= 2) {
	   int len1 = doubleArrays[0].length;
	   int len2 = doubleArrays[1].length;
	   int newlen = len1 * len2;
	   String[] temp = new String[newlen];
	   int index = 0;
	   for (int i = 0; i < len1; i++) {
	    for (int j = 0; j < len2; j++) {
	     temp[index] = doubleArrays[0][i] + "|" + doubleArrays[1][j];
	     index++;
	    }
	   }
	   String[][] newArray = new String[len - 1][];
	   for (int i = 2; i < len; i++) {
	    newArray[i - 1] = doubleArrays[i];
	   }
	   newArray[0] = temp;
	   return doExchange(newArray);
	  } else {
	   return doubleArrays;
	  }

 }

}
以下是一个实现将大小为mustPass_num的一维数组mustPass[mustPass_num]的全排列二维数组arrays[factorial(mustPass_num)][mustPass_num]输出的c函数,它不允许c99: ``` #include <stdio.h> int factorial(int n) { int result = 1; while (n > 1) { result *= n--; } return result; } void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void permute(int *mustPass, int mustPass_num, int **arrays, int *index) { if (mustPass_num == 1) { for (int i = 0; i < mustPass_num; i++) { arrays[*index][i] = mustPass[i]; } (*index)++; return; } for (int i = 0; i < mustPass_num; i++) { swap(&mustPass[i], &mustPass[mustPass_num - 1]); permute(mustPass, mustPass_num - 1, arrays, index); swap(&mustPass[i], &mustPass[mustPass_num - 1]); } } void printArrays(int **arrays, int count, int size) { for (int i = 0; i < count; i++) { for (int j = 0; j < size; j++) { printf("%d ", arrays[i][j]); } printf("\n"); } } void permuteArrays(int *mustPass, int mustPass_num, int **arrays) { int count = factorial(mustPass_num); int index = 0; permute(mustPass, mustPass_num, arrays, &index); printArrays(arrays, count, mustPass_num); } int main() { int mustPass[] = {1, 2, 3}; int mustPass_num = sizeof(mustPass) / sizeof(int); int **arrays = (int **)malloc(factorial(mustPass_num) * sizeof(int *)); for (int i = 0; i < factorial(mustPass_num); i++) { arrays[i] = (int *)malloc(mustPass_num * sizeof(int)); } permuteArrays(mustPass, mustPass_num, arrays); for (int i = 0; i < factorial(mustPass_num); i++) { free(arrays[i]); } free(arrays); return 0; } ``` 这个函数首先计算出数组的全排列的数量,然后创建一个二维数组来存储这些排列。它使用递归来生成数组的所有排列,并将它们存储在二维数组中。最后,它打印出所有排列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值