Number of ways to arrange N numbers which are in a range from 1 to K under given constraints . | Java program to calculate number of ways to arrange N numbers under given constraints . ; Function to print Total number of ways ; If the First number and the last number is same . ; DP approach to find current state with the help of previous state . ; Driver Code ; Function call
import java . io . * ; import java . util . * ; class GFG { static void NumberOfWays ( int n , int k , int p , int q ) { int [ ] [ ] dp = new int [ n ] [ 2 ] ; if ( p == q ) { dp [ 0 ] [ 0 ] = 1 ; dp [ 0 ] [ 1 ] = 0 ; } else { dp [ 0 ] [ 0 ] = 0 ; dp [ 0 ] [ 1 ] = 1 ; } for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] [ 0 ] = dp [ i - 1 ] [ 1 ] ; dp [ i ] [ 1 ] = ( dp [ i - 1 ] [ 0 ] * ( k - 1 ) ) + ( dp [ i - 1 ] [ 1 ] * ( k - 2 ) ) ; } System . out . println ( dp [ n - 1 ] [ 0 ] ) ; } public static void main ( String args [ ] ) { int N = 5 ; int K = 3 ; int P = 2 ; int Q = 1 ; NumberOfWays ( N , K , P , Q ) ; } }