stack.h
#ifndef _STACK_H__
#define _STACK_H__
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
enum DIRE{R,D,L,U,N};
typedef struct Pos{
int x; //行
int y; //列
enum DIRE dire;//方向
}Pos;
//typedef Pos T;
typedef int T;
typedef struct Stack{
T *base;
size_t capcity;
size_t size;
}Stack;
int stack_init(Stack *s,size_t cap); //初始化堆栈
bool stack_is_empty(Stack *s); //判断堆栈是否为空
bool stack_is_full(Stack *s); //判断堆栈是否满
T stack_top(Stack *s); //查看堆栈的栈顶元素
T stack_pop(Stack *s); //从堆栈中弹出一个元素
void stack_push(Stack *s,T data); //往堆栈中压入一个元素
void stack_destroy(Stack *s); //销毁堆栈
void stack_clear(Stack *s); //清空堆栈
void stack_foreach(Stack *s,void (*foreach)(T)); //遍历堆栈中的元素
#endif //_STACK_H__
stack.c
#include "stack.h"
int stack_init(Stack *s,size_t cap){
s->base = calloc(cap,sizeof(T));
if(s->base==NULL){
return -1;
}
s->capcity = cap;
s->size = 0;
return 0;
}
bool stack_is_empty(Stack *s){
return s->size == 0;
}
bool stack_is_full(Stack *s){
return s->size == s->capcity;
}
T stack_top(Stack *s){
return s->base[s->size-1];
}
T stack_pop(Stack *s){
return s->base[--s->size];
}
void stack_push(Stack *s,T data){
s->base[s->size++] = data;
}
void stack_destroy(Stack *s){
free(s->base);
s->base = NULL;
}
void stack_clear(Stack *s){
s->size = 0;
}
void stack_foreach(Stack *s,void (*foreach)(T)){
int i;
for(i=0;i<s->size;i++){
foreach(s->base[i]);
}
}
resolve.c
#include <stdio.h>
#include "stack.h"
Stack s;
//6 2
//1 + (5,1)
//2 + (4,1)
void print(T data){
printf("%d ",data);
}
//num分解为cnt个整数相加
void reslove_to_count(int num,size_t cnt){
//先分解出来一个整数n 剩下num-n分解为cnt-1个整数相加
if(cnt == 1){
if(stack_top(&s)<=num){
stack_push(&s,num);
stack_foreach(&s,print);
printf("\n");
stack_pop(&s);
}
}else{//cnt>1
int n=0;//先分解出来的这个n可以取以下的值
for(n=1;n<=(num-n)/(cnt-1);n++){//num-n 要分 cnt-1
if(stack_is_empty(&s)||stack_top(&s)<=n){
stack_push(&s,n);
reslove_to_count(num-n,cnt-1);
stack_pop(&s);
}
}
}
}
void reslove(int num){//把num进行分解
//可以分解为[2,num]个数相加
int cnt=2;
for(;cnt<=num;cnt++){
reslove_to_count(num,cnt);
}
}
int main(){
int num = 0;
printf("请输入要分解的整数:");
scanf("%d",&num);
stack_init(&s,num);
reslove(num);
return 0;
}
运行结果: