我试图解决这个问题:http://www.geeksforgeeks.org/print-all-jumping-numbers-smaller-than-or-equal-to-a-given-value/
下面的程序是我想出来的,但它不清楚,不干净,让人理解可以修改这个解决方案使其不那么复杂吗?
#include <stdio.h>
int calculate_digits(int x)
{
if (x <= 9)
return 1;
int y = calculate_digits(x/10);
return y+1;
}
int add_up(int *a, int size, int can_add)
{
int i, sum=0, mul = 1;
for (i=0;i<=size;i++) {
sum = sum*mul + a[i];
mul = 10;
}
return sum*10+can_add;
}
int j;
int output[100];
int foo(int x, int index , int value, int size, int j)
{
if (x <= 10 || value >= 10)
return 11;
if (index >= size) {
int i;
for (i=0;i<j;i++)
printf("%d", output[i]);
printf("\n");
printf("next output\n\n");
return 0;
}
if (index == 0) {
int k;
for (k=1;k<=9;k++) {
output[0] = k;
foo(x, 1, k+1, size, 1);
foo(x, 1, k-1, size, 1);
}
} else if (abs(output[index-1]-value) == 1){
if (add_up(output, index-1, value) <= x) {
output[index] = value;
foo(x, index+1, value+1, size, j+1);
} else {
foo(x, index+1, value+1, size, j);
}
} else
foo(x, index+1, value, size, j);
}
int main(void) {
printf("%d\n", foo(105, 0, 0, calculate_digits(105), 0));
return 0;
}
我正在寻找更好的递归解决方案,或者如果可能的话,可以有人修改这段代码,使它更好。
最佳答案
我想你在找这样的东西:
void jumpingc(int current, int max) {
if (current <= max) {
printf("%d ", current);
int ld = current % 10;
if (ld > 0)
jumpingc(current * 10 + ld - 1, max);
if (ld < 9)
jumpingc(current * 10 + ld + 1, max);
}
}
void jumping(int max) {
printf("%d ", 0);
for (int i = 1; i <= 9; i++)
jumpingc(i, max);
}
int main(void) {
int max = 105;
jumping(max);
return 0;
}