Given three positive integer n, s and k. The task is to print all possible sequence of length s, starting with n and the absolute difference between consecutive element is less than k.
Input : n = 5, s = 3, k = 2 Output : 5 5 5 5 5 6 5 5 4 5 6 6 5 6 7 5 6 5 5 4 4 5 4 5 5 4 3 Input : n = 3, s = 2, k = 1 Output : 3 3
Observe, to get the absolute difference between consecutive element less than k, we can increase from 0 to k – 1. Similarly, we can decrease the next element from 1 to k – 1.
Now, to form the required sequence, we will first push ‘n’ to the vector. And then try to fill the other element of the sequence by making recursive call for each element in the sequence. At each recursive call we run a loop from 0 to k – 1 and add (n + i) to the sequence. Once we make the sequence of size ‘s’, we will print the whole sequence and return back to the recursively calling function and remove (n + i).
Similarly, we can run loop from 1 to k – 1 and insert (n – i) to next element position.
To check the number of remaining element required we will pass size – 1 to recursive call and when size become 0, we will print the whole sequence.
Below is the implementation of this approach:
5 5 5 5 5 6 5 5 4 5 6 6 5 6 7 5 6 5 5 4 4 5 4 5 5 4 3
- Print all non-increasing sequences of sum equal to a given number x
- Print all longest common sub-sequences in lexicographical order
- Print all increasing sequences of length k from first n natural numbers
- Count of non-empty sequences of a String
- Count all sub-sequences having product <= K - Recursive approach
- Mutual Recursion with example of Hofstadter Female and Male sequences
- Find all even length binary sequences with same sum of first and second half bits
- Burn the binary tree starting from the target node
- Distinct strings such that they contains given strings as sub-sequences
- 1 to n bit numbers with no consecutive 1s in binary representation.
- Generate all binary strings without consecutive 1's
- Longest consecutive sequence in Binary tree
- Count ways to reach a score using 1 and 2 with no consecutive 2s
- Print sums of all subsets of a given set
- Print all subsequences of a string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.