Split--Search and backtracking

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.