We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
note: it is a litte confuse when Q ask me to print -1 but my code required to return [-1] insteads
functionkFactorization(n:number,A:number[]):number[]{/** * ya, every recursive function need a memorize */constmemorize:{[n:number]:number[]}={}/** * recursive function calculate reverseFactorization * * + number [n] is number need to calculate * -> return [n*] that is smallest possible way to go, until 1 */constreverseFactorization=(n:number):number[]=>{// way end. return itseftif(n==1)return[n]// already memorized, skip calculationif(ninmemorize)returnmemorize[n]// calculate all possible way can go, only get the sortest way and "lexicographically"// memorizedreturnmemorize[n]=A.filter(a=>n%a==0).map(b=>[...reverseFactorization(n/b),n]).sort((a,b)=>{// the sorter lengthif(a.length!=b.length)returna.length-b.length// the top lexicographicallyelse{for(leti=0;i<a.length;i++){if(a[i]<b[i])return-1;if(a[i]>b[i])return1;}return0}}).shift()??[]}// doing recursive reverseFactorization with stating is [n]letrs=reverseFactorization(n)// returnif(rs.length==0||rs[0]!=1)return[-1]returnrs}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
K Factorization
You are viewing a single comment's thread. Return to all comments →
My answer in Typescript, note includes.
note: it is a litte confuse when Q ask me to print -1 but my code required to return [-1] insteads