Number of Permutations such that no Three Terms forms Increasing Subsequence
Last Updated :
01 Sep, 2022
Given a number N. The task is to find the number of permutations of 1 to N such that no three terms of the permutation form an increasing subsequence.
Examples:
Input : N = 3
Output : 5
Valid permutations : 132, 213, 231, 312 and 321 and not 123
Input : N = 4
Output : 14
The above problem is an application of Catalan numbers. So, the task is to only find the nth Catalan Number. First few Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, … (considered from 0th number)
Below is the program to find Nth Catalan Number:
C++
#include <bits/stdc++.h>
using namespace std;
unsigned long int binomialCoeff(unsigned int n,
unsigned int k)
{
unsigned long int res = 1;
if (k > n - k)
k = n - k;
for ( int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
unsigned long int catalan(unsigned int n)
{
unsigned long int c = binomialCoeff(2 * n, n);
return c / (n + 1);
}
int main()
{
int n = 3;
cout << catalan(n) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static long binomialCoeff( long n, long k)
{
long res = 1 ;
if (k > n - k)
k = n - k;
for ( int i = 0 ; i < k; ++i)
{
res *= (n - i);
res /= (i + 1 );
}
return res;
}
static long catalan( long n)
{
long c = binomialCoeff( 2 * n, n);
return c / (n + 1 );
}
public static void main (String[] args)
{
int n = 3 ;
System.out.println(catalan(n));
}
}
|
Python3
def binomialCoeff(n, k):
res = 1
if k > n - k:
k = n - k
for i in range (k):
res = res * (n - i)
res = res / / (i + 1 )
return res
def catalan(n):
c = binomialCoeff( 2 * n, n)
return c / / (n + 1 )
n = 3
print (catalan(n))
|
C#
using System;
class GFG
{
static long binomialCoeff( long n,
long k)
{
long res = 1;
if (k > n - k)
k = n - k;
for ( int i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
static long catalan( long n)
{
long c = binomialCoeff(2 * n, n);
return c / (n + 1);
}
public static void Main (String[] args)
{
int n = 3;
Console.WriteLine(catalan(n));
}
}
|
PHP
<?php
function binomialCoeff( $n , $k )
{
$res = 1;
if ( $k > $n - $k )
$k = $n - $k ;
for ( $i = 0; $i < $k ; $i ++)
{
$res = $res * ( $n - $i );
$res = $res / ( $i + 1);
}
return $res ;
}
function catalan( $n )
{
$c = binomialCoeff(2 * $n , $n );
return $c / ( $n + 1);
}
$n = 3;
print (catalan( $n ));
?>
|
Javascript
<script>
function binomialCoeff(n, k)
{
var res = 1;
if (k > n - k)
k = n - k;
for ( var i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
function catalan(n)
{
var c = binomialCoeff(2 * n, n);
return c / (n + 1);
}
var n = 3;
document.write( catalan(n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...