(backtracking) and all non-augmented positive integer and decomposition algorithms for n

Source: Internet
Author: User

The recursive algorithm is used to output positive integers and all non-increasing positive integers of n. For example, when n=5, the non-additive formula is as follows:

5=5

5=4+1

5=3+2

5=3+1+1

5=2+2+1

5=2+1+1+1

5=1+1+1+1+1

The problem of finding a subset can be solved by backtracking method, which is a recursive algorithm with pruning judgment.

Keywords to solve the problem: no increase

The code is implemented as follows:

Array A is used to hold the decomposed sum, that is, a set of decomposition

Sum indicates the number that needs to be exploded

K indicates the K-sum to be decomposed

#include <iostream>#include<stdio.h>using namespacestd;#defineN 100voidSubsetofsumn (intA[],intSumintk) {     for(inti=sum;i>=1; i--){        if(i<=a[k-1]) {A[k]=i; if(i==sum) {printf ("%d=%d", a[0],a[1]);  for(intp=2;p <=k;p++) printf ("+%d", A[p]); printf ("\ n"); }            ElseSubsetofsumn (A,sum-i,k+1); }    }}intMain () {intN,a[n]; printf ("Please input an integer n (1<=n<=20):"); scanf ("%d",&N); a[0]=N; printf ("The result of nondescend integer factorization is:\n"); Subsetofsumn (A,n,1); return 0;}

(backtracking) and all non-augmented positive integer and decomposition algorithms for n

Related Article

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.