java - Minimal number of squared integers that sums to n - how to do it iteratively? -


i trying find minimal number of squared integers sums given number n.

i've solved recursive function, want iteratively.
how use loops instead of recursive method?

 public static arraylist<integer> minlen(int n)     {         // base case of recursion         if (n == 0)             return new arraylist<integer>();          arraylist<integer> best = null;         int bestint = -1;         (int = 1; i*i <= n; ++i)         {             // check happens if use i^2 part of our representation              arraylist<integer> guess = minlen(n - i*i);             system.out.println("i:"+i);             system.out.println("guess"+guess);             // if haven't selected 'best' yet (best == null)             // or if our new guess better current choice (guess.size() < best.size())             // update our choice of best             if (best == null || guess.size() < best.size())             {                 best = guess;                 system.out.println("best"+best);                  bestint = i;                 system.out.println("bestint"+bestint);             }         }          best.add(bestint);         system.out.println("bestint"+bestint);         system.out.println("best"+best);         return best;     } 

this can solves using dynamic programming loops

the problem solving finding minimal number of squared integers sums n.

it can solved in dynamic programming following pseudo code:

int[] sol = new int[n+1]; //init: sol[0] = 0; (int = 1; <= n; i++) sol[i] = integer.max_value; //fill value each in increasing order: (int =1; <= n; i++)    (int j = 1; j*j <= i; j++)           //make sure sol[i] contains best possible solution           sol[i] = math.min(sol[i], sol[i-j*j] + 1); 

the above gives minimal possible number (sol[n] answer), squared number themselves:

list<integer> numbers = new arraylist<>(); int curr = n; //while haven't 'exhausted' number: while (curr > 0) {      //check numbers have added     (int j=1; j*j <= curr ; j++) {          if found correct number used:          if (sol[curr  - j*j] == sol[curr ] - 1) {                 //add solution, reduce curr , repeat                numbers.add(j);                curr = curr - j*j;                break;          }     } } 

the idea to repeat steps of dp solution, , repeat choices made along way.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -