用递归怎么写
7=1+6;
7=1+1+5
7=1+1+1+4
...
7=2+5
7=2+2+2+1
7=3+4
[解决办法]
/****************************//* zhengshu caifen *//* pclvmm *//* 2012-04-06 11:31 *//****************************/#include <stdio.h>#define N 100static int res[N];void display(int n){ int i; for(i=0; i<n; i++) printf("%-5d",res[i]); printf("\n");}int cf(int n,int m){ int i; if(0 == n) { display(m); return 0; } for(i = n; i>0; i--) { if(0 == m || i <= res[m-1]) { res[m] = i; cf(n-res[m],m+1); } } return 1;}int main(){ cf(5,0); return 0;}
[解决办法]
我试试彩色代码
#include <iostream>#include<stdio.h>#include<stdlib.h>#include <string.h>#define buf_sz 80using namespace std;typedef char N_Str[buf_sz];void apnd_str(char* source,char* conect,int num){ N_Str tmp; strcat(source,conect); itoa(num,tmp,10); strcat(source,tmp); return;}void sep(int kept, int to_be_sep, char* str_show){ N_Str tmp; int new_kept,new_to_sep; if (to_be_sep==1) { cout<<str_show<<"+1"<<endl; return; } N_Str to_show; strcpy(to_show ,str_show); if (kept>=to_be_sep) { apnd_str(to_show,"+",to_be_sep); cout<<to_show<<endl; strcpy(to_show ,str_show); } for (new_kept=to_be_sep-1;new_kept>=1;--new_kept) { new_to_sep = to_be_sep-new_kept; if (kept>=new_kept) { char *next_show = new N_Str; strcpy(next_show ,to_show); apnd_str(next_show,"+",new_kept); sep(new_kept,new_to_sep,next_show); delete[] next_show; } } return;}void do_sep(int to_be_sep){ N_Str num_str; N_Str head; itoa(to_be_sep,num_str,10); strcpy(head,num_str); strcat(head ,"="); for (int kept=to_be_sep-1;kept>=1;--kept) { N_Str show_str; strcpy(show_str ,head); itoa(kept,num_str,10); strcat(show_str ,num_str); int rest = to_be_sep - kept; sep(kept,rest,show_str); } return;}int main(){ do_sep(7); getchar(); return 1;}