You are viewing a single comment's thread. Return to all comments →
In order to solve this problem, first you need to know how to use dp to solve permuation problem. ex: N=3, dp[i][j], i means total numbers, j means last element. (j<=i) dp[1][1] = 1 //1 dp[2][1] = sum(dp[1]); //(1) 1 => 2 1 (replace 1 with 2) dp[2][2] = sum(dp[1]); //1 2 dp[3][1] = sum(dp[2]); //2 (1) 1 => 2 3 1 (replace 1 with 3) //(1) 2 1 => 3 2 1 (replace 1 with 3) dp[3][2] = sum(dp[2]); //(2) 1 2 => 3 1 2 (replace 2 with 3) //1 (2) 2 => 1 3 2 (replace 2 with 3) dp[3][3] = sum(dp[2]); //2 1 3 //1 2 3 total permutation is sum(dp[3]) = 6. Now we need to think about constraints a and b. We can define as following: a(i)=1 as a has ith position element b(i)=1 as b has ith position element. There are total three situations for dp[i][j]: if a(i) == 1 or b(i-1) == 1 (include only bigger sets) sum(dp[i-1][j] + dp[i-1][j+1] ... dp[i-1][i-1]) else if b(i) == 1 or a(i-1) == 1 (include only smaller sets) sum(dp[i-1][1] + dp[i-1][2] ... dp[i-1][j-1]) else sum(dp[i-1]) Ex: N = 4 a1 = 2 and b1 = 3. The 5 permutations of {1,2,3,4} that satisfy the condition are 2 1 4 3 3 2 4 1 4 2 3 1 3 1 4 2 4 1 3 2 dp[1][1] = 1 //1 -------------------------------------------------------------- a(2) = 1 dp[2][2] = 0 //j=2, no bigger sets dp[2][1] = dp[1][1] //(1) 1 => 2 1 --------------------------------------------------------------- b(3) = 1 dp[3][3] = dp[2][2] //0 + dp[2][1] //2 1 3 dp[3][2] = dp[2][1] //(2) 1 2 => 3 1 2 dp[3][1] = 0 //j=1, no smaller sets --------------------------------------------------------------- b(3) = 1 dp[4][4] = 0 //j=4, no bigger sets dp[4][3] = dp[3][3] //2 1 (3) 3 => 2 1 4 3 dp[4][2] = dp[3][3] //(2) 1 3 2 => 4 1 3 2 +dp[3][2] //3 1 (2) 2 => 3 1 4 2 dp[4][1] = dp[3][3] //2 (1) 3 1 => 2 4 3 1 => 4 2 3 1 +dp[3][2] //3 (1) 2 1 => 3 4 2 1 => 3 2 4 1 +dp[3][1] //0 You may realize we can always change order of dp[i-1], because total permutation doesn't change. ex: 2 1 3, we have relationship 2 > 1 < 3 after change to 2 4 3, we can always have same relationship 4 > 2 < 3. result sum(dp[4]) = 5
Seems like cookies are disabled on this browser, please enable them to open this website
Extremum Permutations
You are viewing a single comment's thread. Return to all comments →