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.
I coded in Java, using backtracking as the core algorithm in the solution. This can be improved.
I recommend this problem for anyone who just learn backtracking.
publicstaticintpowerSum(intX,intN){// Write your code herereturnpowerSum(X,N,0);}staticintpowerSum(intX,intN,intmin){/* My solution: try, check and try again (backtracking) Base cases: X < 0 -> try but fail (+0) -> try again X == 0 -> try and find (+1) -> continues try ** Numbers tried must be increment, starting at least with 1. -> Reduces duplicate cases. Induction steps: Find satisfied numbers, try one of them (k) Minus X to k^N(1 case - 1 subproblem) Time complex: O((floor(log_N(X)))!) */if(X<0){return0;}if(X==0){return1;//true because of (X >= 1) condition}intcount=0;inti=min+1;while(exp(i,N)<=X){//O(log_N(X))count+=powerSum(X-exp(i,N),N,i);i++;}returncount;}privatestaticintexp(intn,intN){intex=n;for(inti=1;i<N;i++){n*=ex;}returnn;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
The Power Sum
You are viewing a single comment's thread. Return to all comments →
I coded in Java, using backtracking as the core algorithm in the solution. This can be improved. I recommend this problem for anyone who just learn backtracking.