Reputation: 95
Say there is a vector of int. Now we want to merge such that , we select 2 adjacent element v[I] and v[I+1] ( for each valid I ) and do v[I] = v[I+1] + v[I] . And erase v[I+1]. Keep on doing this until you're just left with one element in the vector.(Note I=0 & I=v.size()-1 are also considered as adjacent ). so we need to try all such possible combination(i.e which pair we took first and merged matters if further clarification required please let me know in the comment)
where every time we merge we do cost+= v[I] + v[I+1].Goal is to minimise cost.Take an example say vector is 1 2 3. merging [1 2 3]-> [3,3] & cost=3 -> [6] & cost=9 another way [1 2 3]-> [1,5] & cost=5 -> [6] & cost=11 . So is their any algorithm to generate all permutation with given constrain ?
#include<bits/stdc++.h>
using namespace std;
int mn =INT_MAX;
void r(vector<int > v, int sum)
{
if(v.size()==1){if( mn >sum) mn=sum; return ;}
for(int i=0;i<v.size();i++)
{
sum+=v[i]+v[(i+1)%v.size()];
v[i]=v[i]+v[(i+1)%v.size()];
v.erase(v.begin()+(i+1)%v.size());
r(v,sum);
}
}
int main()
{
vector<int> v;//suppose we gave some input to our vector
r(v,0);
cout<<mn;
return 0;
}
#if you have a better solution, do state it, thankyou!
Upvotes: 4
Views: 209
Reputation: 26753
Your goal is to impress interviewers.
They are looking for people who can work in teams and can make reusable code, which can be handed over to colleagues when needing to be switched to a different topic to work on.
For that, learn to
Upvotes: 5