You are given an array of n elements [1,2,....n]. For example {3,2,1,6,7,4,5}.
Now we create a signature of this array by comparing every consecutive pir of elements. If they increase, write I else write D. For example for the above array, the signature would be "DDIIDI". The signature thus has a length of N-1. Now the question is given a signature, compute the lexicographically smallest permutation of [1,2,....n]. Write the below function in language of your choice.
Now we create a signature of this array by comparing every consecutive pir of elements. If they increase, write I else write D. For example for the above array, the signature would be "DDIIDI". The signature thus has a length of N-1. Now the question is given a signature, compute the lexicographically smallest permutation of [1,2,....n]. Write the below function in language of your choice.
vector* FindPermute(const string& signature);
vector<int> smallestPermutation;
void dfs(vector<int> &res, string &str, int cur)
{
if(smallestPermutation.size() == res.size())
return;
if(cur < res.size())
{
for(int i = cur; i < res.size(); ++i)
{
swap(res[cur], res[i]);
if(cur > 0)
{
if('D' == str[cur-1] && res[cur] < res[cur-1])
dfs(res, str, cur + 1);
else if('I' == str[cur-1] && res[cur] > res[cur-1])
dfs(res, str, cur + 1);
}
else
dfs(res, str, cur + 1);
swap(res[cur], res[i]);
}
}
else
smallestPermutation = res;
}
vector<int> SmallestPermutation(string &str)
{
int size = str.size();
vector<int> res;
for(int i = 0; i <= size; ++i)
res.push_back(i+1);
dfs(res, str, 0);
return res;
}
int main()
{
vector<int> perm = SmallestPermutation(string("DDIIDI"));
return 0;
}