Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Maximize sum of all elements which are not a part of the Longest Increasing Subsequence
Next article icon

Print all non-increasing sequences of sum equal to a given number x

Last Updated : 10 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number x, print all possible non-increasing sequences with sum equals to x.

Examples: 

Input: x = 3 Output: 1 1 1         2 1         3  Input: x = 4 Output: 1 1 1 1         2 1 1         2 2         3 1         4


We strongly recommend you to minimize your browser and try this yourself first.
The idea is to use a recursive function, an array arr[] to store all sequences one by one and an index variable curr_idx to store current next index in arr[]. Below is algorithm.
1) If current sum is equal to x, then print current sequence. 
2) Place all possible numbers from 1 to x-curr_sum numbers at curr_idx in array. Here curr_sum is sum of current elements in arr[]. After placing a number, recur for curr_sum + number and curr_idx+1.

Below is the implementation of above steps. 

C++
// C++ program to generate all non-increasing // sequences of sum equals to x #include<bits/stdc++.h> using namespace std;  // Utility function to print array // arr[0..n-1] void printArr(int arr[], int n) {     for(int i = 0; i < n; i++)       cout << arr[i] << " ";     cout << endl; }  // Recursive Function to generate all // non-increasing sequences // with sum x // arr[]    --> Elements of current sequence // curr_sum --> Current Sum // curr_idx --> Current index in arr[] void generateUtil(int x, int arr[], int curr_sum,                                     int curr_idx) {         // If current sum is equal to x,     // then we found a sequence    if (curr_sum == x)    {       printArr(arr, curr_idx);       return;    }     // Try placing all numbers from     // 1 to x-curr_sum at current index    int num = 1;     // The placed number must also be     // smaller than previously placed    // numbers and it may be equal to     // the previous stored value, i.e.,    // arr[curr_idx-1] if there exists    // a previous number    while (num <= x - curr_sum &&          (curr_idx == 0 ||            num <= arr[curr_idx - 1]))    {                // Place number at curr_idx        arr[curr_idx] = num;         // Recur        generateUtil(x, arr, curr_sum + num,                             curr_idx + 1);         // Try next number        num++;    } }  // A wrapper over generateUtil() void generate(int x) {          // Array to store sequences one by one     int arr[x];      generateUtil(x, arr, 0, 0); }  // Driver code int main() {     int x = 5;     generate(x);     return 0; } 
Java
// Java program to generate all non-increasing // sequences of sum equals to x class GFG {          // Utility function to print array     // arr[0..n-1]     static void printArr(int arr[], int n)     {         for (int i = 0; i < n; i++)             System.out.printf("%d ", arr[i]);                      System.out.println("");     }          // Recursive Function to generate all      // non-increasing sequences with sum x     // arr[] --> Elements of current sequence     // curr_sum --> Current Sum     // curr_idx --> Current index in arr[]     static void generateUtil(int x, int arr[],                      int curr_sum, int curr_idx)     {                  // If current sum is equal to x, then         // we found a sequence         if (curr_sum == x)         {             printArr(arr, curr_idx);             return;         }                  // Try placing all numbers from 1 to          // x-curr_sum at current index         int num = 1;                  // The placed number must also be             // smaller than previously placed            // numbers and it may be equal to             // the previous stored value, i.e.,            // arr[curr_idx-1] if there exists            // a previous number         while (num <= x - curr_sum &&                               (curr_idx == 0 ||                      num <= arr[curr_idx - 1]))         {                          // Place number at curr_idx             arr[curr_idx] = num;                      // Recur             generateUtil(x, arr, curr_sum+num,                                      curr_idx + 1);                      // Try next number             num++;         }     }          // A wrapper over generateUtil()     static void generate(int x)     {                  // Array to store sequences on by one         int arr[] = new int [x];         generateUtil(x, arr, 0, 0);     }          // Driver program     public static void main(String[] args)     {         int x = 5;         generate(x);     } }  // This code is contributed by Smitha. 
Python3
# Python3 program to generate all # non-increasing sequences of sum # equals to x  # Utility function to print array # arr[0..n-1] def printArr(arr, n):      for i in range(0, n):         print(arr[i], end = " ")              print("")   # Recursive Function to generate # all non-increasing sequences # with sum x arr[] --> Elements # of current sequence # curr_sum --> Current Sum # curr_idx --> Current index in # arr[] def generateUtil(x, arr, curr_sum,                          curr_idx):  # If current sum is equal to x, # then we found a sequence     if (curr_sum == x):          printArr(arr, curr_idx)         return       # Try placing all numbers from      # 1 to x-curr_sum at current     # index     num = 1          # The placed number must also be      # smaller than previously placed     # numbers and it may be equal to      # the previous stored value, i.e.,     # arr[curr_idx-1] if there exists     # a previous number     while (num <= x - curr_sum and                  (curr_idx == 0 or            num <= arr[curr_idx - 1])):          # Place number at curr_idx         arr[curr_idx] = num              # Recur         generateUtil(x, arr,              curr_sum + num, curr_idx + 1)              # Try next number         num += 1    # A wrapper over generateUtil() def generate(x):      # Array to store sequences     # on by one     arr = [0] * x     generateUtil(x, arr, 0, 0)   # Driver program x = 5 generate(x)  # This code is contributed # by Smitha. 
C#
// C# program to generate all non-increasing // sequences of sum equals to x using System;  class GFG {           // Utility function to print array     // arr[0..n-1]     static void printArr(int []arr, int n)     {         for (int i = 0; i < n; i++)             Console.Write( arr[i]);                       Console.WriteLine();     }           // Recursive Function to generate all      // non-increasing sequences with sum x     // arr[] --> Elements of current sequence     // curr_sum --> Current Sum     // curr_idx --> Current index in arr[]     static void generateUtil(int x, int []arr,                      int curr_sum, int curr_idx)     {                   // If current sum is equal to x, then         // we found a sequence         if (curr_sum == x)         {             printArr(arr, curr_idx);             return;         }                   // Try placing all numbers from 1 to          // x-curr_sum at current index         int num = 1;                   // The placed number must also be          // smaller than previously placed            // numbers and it may be equal to             // the previous stored value, i.e.,            // arr[curr_idx-1] if there exists            // a previous number         while (num <= x - curr_sum &&                               (curr_idx == 0 ||                      num <= arr[curr_idx - 1]))         {                           // Place number at curr_idx             arr[curr_idx] = num;                       // Recur             generateUtil(x, arr, curr_sum+num,                                      curr_idx + 1);                       // Try next number             num++;         }     }           // A wrapper over generateUtil()     static void generate(int x)     {                   // Array to store sequences on by one         int []arr = new int [x];         generateUtil(x, arr, 0, 0);     }           // Driver program     public static void Main()     {         int x = 5;         generate(x);     } }   // This code is contributed by nitin mittal. 
PHP
<?php // PHP program to generate all  // non-increasing sequences // of sum equals to x  // function to print array  // arr[0..n-1] function printArr($arr, $n) {     for ($i = 0; $i < $n; $i++)     echo $arr[$i] , " ";     echo " \n"; }  // Recursive Function to generate // all non-increasing sequences // with sum x // arr[] --> Elements of current sequence // curr_sum --> Current Sum // curr_idx --> Current index in arr[] function generateUtil($x, $arr, $curr_sum,                                 $curr_idx) {          // If current sum is equal to x,     // then we found a sequence     if ($curr_sum == $x)     {         printArr($arr, $curr_idx);         return;     }          // Try placing all numbers from      // 1 to x-curr_sum at current index     $num = 1;          // The placed number must also be      // smaller than previously placed     // numbers and it may be equal to      // the previous stored value, i.e.,     // arr[curr_idx-1] if there exists     // a previous number     while ($num <= $x - $curr_sum and            ($curr_idx == 0 or $num <=                  $arr[$curr_idx - 1]))     {           // Place number at curr_idx         $arr[$curr_idx] = $num;              // Recur         generateUtil($x, $arr, $curr_sum +                       $num, $curr_idx + 1);              // Try next number         $num++;     } }  // A wrapper over generateUtil() function generate($x) {     // Array to store      // sequences on by one     $arr = array();      generateUtil($x, $arr, 0, 0); }      // Driver Code     $x = 5;     generate($x);  // This code is contributed by anuj_67. ?> 
JavaScript
<script>  // Javascript program to generate all  // non-increasing sequences of sum equals to x  // Utility function to print array // arr[0..n-1] function printArr(arr, n) {     for(let i = 0; i < n; i++)         document.write(arr[i] + " ");                document.write("</br>"); }    // Recursive Function to generate all // non-increasing sequences with sum x // arr[] --> Elements of current sequence // curr_sum --> Current Sum // curr_idx --> Current index in arr[] function generateUtil(x, arr, curr_sum, curr_idx) {          // If current sum is equal to x, then     // we found a sequence     if (curr_sum == x)     {         printArr(arr, curr_idx);         return;     }            // Try placing all numbers from 1 to     // x-curr_sum at current index     let num = 1;            // The placed number must also be     // smaller than previously placed     // numbers and it may be equal to     // the previous stored value, i.e.,     // arr[curr_idx-1] if there exists     // a previous number     while (num <= x - curr_sum &&           (curr_idx == 0 ||            num <= arr[curr_idx - 1]))     {                  // Place number at curr_idx         arr[curr_idx] = num;                // Recur         generateUtil(x, arr, curr_sum + num,                              curr_idx + 1);                // Try next number         num++;     } }    // A wrapper over generateUtil() function generate(x) {          // Array to store sequences on by one     let arr = new Array(x);     generateUtil(x, arr, 0, 0); }  // Driver code    let x = 5;  generate(x);    // This code is contributed by divyeshrabadiya07       </script> 

Output: 

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

 


Next Article
Maximize sum of all elements which are not a part of the Longest Increasing Subsequence

A

Ashish Gupta
Improve
Article Tags :
  • Mathematical
  • Recursion
  • DSA
  • combinatorics
Practice Tags :
  • Mathematical
  • Recursion

Similar Reads

  • Count number of increasing sub-sequences : O(NlogN)
    Given an array arr[] of length N, the task is to find the number of strictly increasing sub-sequences in the given array. Examples: Input: arr[] = {1, 2, 3} Output: 7 All increasing sub-sequences will be: 1) {1} 2) {2} 3) {3} 4) {1, 2} 5) {1, 3} 6) {2, 3} 7) {1, 2, 3} Thus, answer = 7Input: arr[] =
    12 min read
  • Print all n-digit numbers whose sum of digits equals to given sum
    Given number of digits n, print all n-digit numbers whose sum of digits adds upto given sum. Solution should not consider leading 0’s as digits.Examples: Input: N = 2, Sum = 3Output: 12 21 30Input: N = 3, Sum = 6Output: 105 114 123 132 141 150 204 213 222 231 240 303 312 321 330 402 411 420 501 510
    10 min read
  • Minimize the number of strictly increasing subsequences in an array | Set 2
    Given an array arr[] of size N, the task is to print the minimum possible count of strictly increasing subsequences present in the array. Note: It is possible to swap the pairs of array elements. Examples: Input: arr[] = {2, 1, 2, 1, 4, 3}Output: 2Explanation: Sorting the array modifies the array to
    6 min read
  • Maximize sum of all elements which are not a part of the Longest Increasing Subsequence
    Given an array arr[], the task is to find the maximum sum of all the elements which are not a part of the longest increasing subsequence. Examples: Input: arr[] = {4, 6, 1, 2, 3, 8} Output: 10 Explanation: Elements are 4 and 6 Input: arr[] = {5, 4, 3, 2, 1} Output: 14 Explanation: Elements are 5, 4,
    8 min read
  • Print all n-digit strictly increasing numbers
    Given number of digits n in a number, print all n-digit numbers whose digits are strictly increasing from left to right.Examples: Input: n = 2 Output: 01 02 03 04 05 06 07 08 09 12 13 14 15 16 17 18 19 23 24 25 26 27 28 29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89 Input: n = 3 O
    6 min read
  • Generate sequence with equal sum of adjacent integers
    Given an integer N, find a sequence of N integers such that the sum of all integers in the sequence is equal to the sum of any two adjacent integers in the sequence. Examples: Input: N = 4Output: 1 -1 1 -1Explanation: Total sum of the four integers is 0 and the sum of any two adjacent integers is al
    8 min read
  • Sum of numbers from 1 to N which are in Fibonacci Sequence
    Given an integer N, the task is to find the sum of numbers from 1 to N which are in Fibonacci sequence. First few Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, ....Examples: Input: N = 5 Output: 12 1 + 1 + 2 + 3 + 5 = 12Input: N = 10 Output: 20 1 + 1 + 2 + 3 + 5 + 8 = 20 Approach: Loop through
    4 min read
  • Find all subsequences with sum equals to K
    Given an array arr[] of length n and a number k, the task is to find all the subsequences of the array with sum of its elements equal to k. Note: A subsequence is a subset that can be derived from an array by removing zero or more elements, without changing the order of the remaining elements. Examp
    7 min read
  • Print all possible K-length subsequences of first N natural numbers with sum N
    Given two positive integers N and K, the task is to print all possible K-length subsequences from first N natural numbers whose sum of elements is equal to N. Examples: Input: N = 5, K = 3 Output: { {1, 1, 3}, {1, 2, 2}, {1, 3, 1}, {2, 1, 2}, {2, 2, 1}, {3, 1, 1} } Explanation: 1 + 1 + 3 = N(= 5) an
    9 min read
  • Number of Longest Increasing Subsequences
    Given an array arr[] of size n, the task is to count the number of longest increasing subsequences present in the given array. Examples: Input: arr[] = [2, 2, 2, 2, 2]Output: 5Explanation: The length of the longest increasing subsequence is 1, i.e. {2}. Therefore, count of longest increasing subsequ
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences