问题描述: 计算从某些输入n上升的所有序列的数量。 所以用户输入n;与N,然后我创建一个数字1..1的数组,然后与属性号序列交替递增/递减序列的计数
例子:n = 4
1 3 2 4
1 4 2 3
2 3 1 4
2 4 1 3
3 4 1 2
答:5
我的程序工作,但由于某种原因我有时得到0而不是答案。
#include <stdio.h>
#include <stdlib.h>
void *safeMalloc(int n) {
void *p = malloc(n);
if (p == NULL) {
printf("Error: malloc(%d) failed. Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return p;
}
void swap(int *fir, int *sec) {
int temp = *fir;
*fir = *sec;
*sec = temp;
}
void permute(int *array, int i, int length, int *count) {
if (length == 2) {
*count = 1;
return;
}
if (length == i) {
int v = 0, flag = 1;
while (v < length) {
if (v % 2 == 0) {
if (array[v] < array[v + 1]) {
v++;
} else {
flag = 0;
return;
}
}
if (v % 2 != 0) {
if (array[v] > array[v + 1]) {
v++;
} else {
flag = 0;
return;
}
}
}
if (flag == 1) {
/*
int a;
for (a = 0; a < length; a++)
printf("%d", array[a]);
printf("\n");
*/
*count = *count + 1;
}
}
int j = i;
for (j = i; j < length; j++) {
swap(array + i, array + j);
permute(array, i + 1, length, count);
swap(array + i, array + j);
}
return;
}
int main(int argc, char **argv) {
int n;
scanf("%d", &n);
int *arr = safeMalloc(n * sizeof(int));
int i;
for (i = 0; i < n; i++) {
arr[i] = i + 1;
}
int count = 0;
permute(arr, 0, n, &count);
printf("%d\n", count);
return 0;
}
'哪里去' - 请解释一下是什么意思? – MBo
目前还不清楚什么“从某些输入”n“意味着什么?这是否意味着类似于:序列'a_1 ... a_k a_ {k + 1} ... a_n'其中'a_1 ... a_k'排序,然后是'a_ {k + 1} ...a_n'被重新排序,但是'a_k> a_ {k + 1}'。排列在哪里发挥作用?另外,使用普通的'malloc'代替'safeMalloc'是安全的。这是不可能的,你会用完内存,你会很快被OOM杀死比在大多数设置中'malloc'返回NULL。 –
看看例子:1 <3> 2 <4。我的意思是,在偶数位置上的数字将总是小于在它们旁边的奇数 –