Title Description Description
Any number of natural numbers greater than 0 can be split into a sum of several natural numbers less than n
input/output format input/output
Input Format:
A positive integer n
output Format:
N=xxx+xxx+xxx+xxx ...Total (number of programmes) =xxx
input and Output sample sample Input/output
sample Test point # #
Input Sample:7
Sample output:
7=1+1+1+1+1+1+1
7=1+1+1+1+1+2
7=1+1+1+1+3
7=1+1+1+2+2
7=1+1+1+4
7=1+1+2+3
7=1+1+5
7=1+2+2+2
7=1+2+4
7=1+3+3
7=1+6
7=2+2+3
7=2+5
7=3+4
Total=14
idea: Code is clear, there is no need to say ~ ~
The code is as follows:
1#include <cstdio>2#include <iostream>3#include <cstdlib>4 using namespacestd;5 inta[10001]={1},n,total;6 intSearchint,int);7 intPrintint);8 intMain ()9 {TenCin>>N; OneSearch (N,1); A //the number n to be split is passed to S -cout<<"total="<<total<<Endl; - //number of scenarios for output splitting the return 0; - } - intSearchintSintt) - { + inti; - for(i=a[t-1];i<=s;i++) + if(i<n)//The current number i is greater than or equal to the first 1 digits, and however n (if just equal to n, there must be one in Addend of 0, illegal, get out! ) A { atA[t]=i;//Increment - //Save the current split number I -s-=i; - //s minus the number I, the value of S will continue to split - if(s==0) print (t); - //Split to end output when S=0 in ElseSearch (s,t+1); - //when s>0, continue to recursion tos+=i; + //backtracking: plus the number of splits so that all possible splits are produced - } the } * intPrintintt) $ {Panax Notoginsengcout<<n<<"="; - for(intI=1; i<=t-1; i++) the //output a split scheme +cout<<a[i]<<"+"; Acout<<a[t]<<Endl; thetotal++; + //number of scenarios cumulative 1 -}
Split--Search and backtracking