我试图找到总和为给定数字n
的最小平方整数。
我用递归函数解决了它,但我想迭代地完成它。
如何使用一些循环而不是递归方法?
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;
for (int i = 1; i*i <= n; ++i)
{
// Check what happens if we use i^2 as part of our representation
ArrayList<Integer> guess = minLen(n - i*i);
System.out.println("i:"+i);
System.out.println("Guess"+guess);
// If we haven't selected a 'best' yet (best == null)
// or if our new guess is better than the 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;
}
答案 0 :(得分:0)
这可以使用带循环的动态编程解决
您正在解决的问题是找到总和为n
的最小平方整数。
可以通过以下伪代码在Dynamic Programming中解决:
int[] sol = new int[n+1];
//init:
sol[0] = 0;
for (int i = 1; i <= n; i++) sol[i] = Integer.MAX_VALUE;
//fill the value for each i in increasing order:
for (int i =1; i <= n; i++)
for (int j = 1; j*j <= i; j++)
//make sure sol[i] contains the best possible solution
sol[i] = Math.min(sol[i], sol[i-j*j] + 1);
上面给出了尽可能少的数字(sol[n]
就是答案),以获得平方数字:
List<Integer> numbers = new ArrayList<>();
int curr = n;
//while we haven't 'exhausted' the number:
while (curr > 0) {
//check all numbers we could have added
for (int j=1; j*j <= curr ; j++) {
if found the correct number we used:
if (sol[curr - j*j] == sol[curr ] - 1) {
//add it to the solution, reduce it from curr and repeat
numbers.add(j);
curr = curr - j*j;
break;
}
}
}
我们的想法是重复您的DP解决方案的步骤,并重复您在此过程中做出的选择。