【发布时间】:2018-03-31 07:18:05
【问题描述】:
问题描述: 计算从某个输入 n 上升的所有序列的数量。 所以用户输入n;用那个 n 然后我创建一个数字数组 1..n 然后用那个属性对序列编号
示例: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;
}
【问题讨论】:
-
which go up down- 请解释一下这是什么意思? -
不清楚“从某个输入
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是安全的。在大多数设置中,您不太可能会用完内存并且您会比让malloc返回 NULL 更早被 OOM 杀死。 -
看例子:12
-
请注意,问题需要此类序列的数量,但不要求明确生成这些序列。你有没有想过用数学方法来计算这个数字。也许,某种动态编程/表格填充?