【发布时间】:2018-05-27 06:07:52
【问题描述】:
有一个算法问题here 关于 n 次方的总和,我尝试使用递归解决问题,但在我在线检查解决方案之前不起作用,我得到了这个:
public class Main {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int x = s.nextInt(), n = s.nextInt();
int end = (int)Math.pow(x, 1.0/n);
System.out.print(sumOfPower(x, n, end));
}
static int sumOfPower(int number, int power, int end) {
int[] temp = new int[number + 1];
temp[0] = 1;
for(int i = 1; i <= end; i++) {
int value = (int)Math.pow(i, power);
for(int j = number; j > value - 1; j--) {
temp[j] += temp[j-value];
}
}
return temp[number];
}
我尝试通过在每个循环中记录结果来研究代码,所以sumOfPower 方法现在看起来像这样:
static int sumOfPower(int number, int power, int end) {
int[] temp = new int[number + 1];
temp[0] = 1;
for(int i = 1; i <= end; i++) {
int value = (int)Math.pow(i, power);
for(int j = number; j > value - 1; j--) {
System.out.println( "j:"+j+"\tj-value:"+(j-value)+ "\ttemp[j]:" + temp[j] + "\ttemp[j-value]:" + temp[j-value] );
temp[j] += temp[j-value];
System.out.println(i + ": " + Arrays.toString(temp));
}
}
return temp[number];
}
我了解循环和动态编程逻辑在某种程度上如何与使用x=10 和n=2 的日志一起工作。日志如下:
10
2
j:10 j-value:9 temp[j]:0 temp[j-value]:0
1: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:9 j-value:8 temp[j]:0 temp[j-value]:0
1: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:8 j-value:7 temp[j]:0 temp[j-value]:0
1: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:7 j-value:6 temp[j]:0 temp[j-value]:0
1: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:6 j-value:5 temp[j]:0 temp[j-value]:0
1: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:5 j-value:4 temp[j]:0 temp[j-value]:0
1: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:4 j-value:3 temp[j]:0 temp[j-value]:0
1: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:3 j-value:2 temp[j]:0 temp[j-value]:0
1: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:2 j-value:1 temp[j]:0 temp[j-value]:0
1: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:1 j-value:0 temp[j]:0 temp[j-value]:1
1: [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:10 j-value:6 temp[j]:0 temp[j-value]:0
2: [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:9 j-value:5 temp[j]:0 temp[j-value]:0
2: [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:8 j-value:4 temp[j]:0 temp[j-value]:0
2: [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:7 j-value:3 temp[j]:0 temp[j-value]:0
2: [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:6 j-value:2 temp[j]:0 temp[j-value]:0
2: [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
j:5 j-value:1 temp[j]:0 temp[j-value]:1
2: [1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0]
j:4 j-value:0 temp[j]:0 temp[j-value]:1
2: [1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0]
j:10 j-value:1 temp[j]:0 temp[j-value]:1
3: [1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
j:9 j-value:0 temp[j]:0 temp[j-value]:1
3: [1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1]
我目前需要知道的是这背后的数学逻辑,我怎么知道循环后temp['number']是x可以表示为nth幂的总和的可能方式的总数唯一的自然数。非常感谢任何帮助。
【问题讨论】:
标签: java algorithm recursion dynamic-programming