Header Ads Widget

Break Numbers | coding Ninjas solution

 Break Numbers

Given an integer n, break it into smaller numbers such that their summation is equal to n. Print all such combinations in different lines.

Note : [1, 2, 1] and [1,1, 2] are same, so print the particular sequence with increasing order. Order of different combinations doesn't matter.
Input format :
Integer n
Output format :
Print all possible combinations in different lines
Constraints :

1 <= n <= 100

Input :

4

Output :

1 1 1 1
1 1 2
1 3
2 2
4

Code(Python):- 

l=[]
def printarray(p,n):
    ll=[]
    for i in range(n):
        ll.append(p[i])
    l.append(ll)

def pp(n):
    p=[0]*n
    k=0
    p[k]=n 
    while True:
        printarray(p,k+1)
        rr=0
        while k>=0 and p[k]==1:
            rr+=p[k]
            k-=1
        if k<0:
            print()
            return
        p[k]-=1
        rr+=1
        while rr>p[k]:
            p[k+1]=p[k]
            rr=rr-p[k]
            k+=1
        p[k+1]=rr 
        k+=1

n=int(input())
pp(n)
for  i in range(len(l)-1,-1,-1):
    ll=l[i]
    for i in range(len(ll)-1,-1,-1):
        print(ll[i],end=" ")
    print()

Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-