I have been given the number N
. I have to find all the permutations of numbers 1..N
such that the total number of inversions in the array is K
.
For example: (all the following permutations have exactly 2 inversions)
N=4 , K=2
(1,4,2,3) , (1,3,4,2) , (2,1,4,3) , (3,1,2,4) and (2,3,1,4).
My Approach:
Dynamic Programming: let dp[i][j]
hold number of ways such that position i
is responsible for j
number of inversion.
dp[n][0]=1
for(int i=n-1;i>=1;i--){
int x = Math.min(k,n-i); // Maximum Number of inversion i position can do
for(int j=0;j<=x;j++){
for(int v=0;v<=j;v++){
dp[i][j]+=dp[i+1][v];
}
}
But my approach give me individual position inversions, how can I get the total ways?