If someone goes up the stairs, one step can buy one step, two steps or three steps, a total of n steps. It is programmed to output all possible methods. For example, n=4
1 1 1 1
1 1 2
1 2 1
1 3
2 1 1
2 2
3 1
According to the meaning of the question, the question can be divided into three situations: one step at a time, two steps at a time, and three steps at a time. In the recursive function, a parameter n needs to be introduced to indicate how many steps are taken each time. Function prototype:
void step(int n)
Use the array queue to store the number of stages on each stage. If you go up a step, store 1 in the array queue, the code is as follows:
queue[index++]=1;
step(n-1);
--index;
If you go up two steps, store 2 in the array queue, the code is as follows:
if(n>1)
{ queue[index++]=2; step(n-2); --index; }
If you go up three steps, store 3 into the array queue, the code:
if(n>2)
{ queue[index++]=3; step(n-3); --index; }
When n=0, output the method of each step up.
Code:
#include<stdio.h>
#include <iostream>
void output();
void step(int n);
#define STAIR_NUM 4
int queue[STAIR_NUM];
int total = 0;
int index;
int main()
{
int step_num=4;
printf("--------------------------------------\n");
printf(" 上台阶的方法 \n");
printf("--------------------------------------\n");
step(step_num);
printf("\n 共有 %d 种方法 \n", total);
getchar();
}
void step(int n)
{
if (n == 0)
{
total++;
printf("---------第%d种方法 ----------\n", total);
output();
return;
}
queue[index++] = 1;
step(n - 1);
--index;
if (n > 1)
{
queue[index++] = 2;
step(n - 2);
--index;
}
if (n > 2)
{
queue[index++] = 3;
step(n - 3);
--index;
}
}
void output()
{
int i;
for (i = 0; i < index; i++)
printf("-%d", queue[i]);
printf("-\n");
}
result: