我正在尝试解决问题而且我编写了解决方案,但显然该程序运行时间太长。如何最大限度地减少它的运行时间?
这是我正在解决的问题:
这是我的代码:
import java.util.Scanner;
public class PebbleSolitaire {
private static int maxDigits = 1 << 23;
private static int[] posSol = new int[maxDigits];
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int cases = reader.nextInt();
reader.nextLine();
for (int caseCount = 0; caseCount < cases; caseCount++) {
int lineInt = 0;
String lineStr = reader.nextLine().trim();
for (int i = 0; i < lineStr.length(); i++) {
if (lineStr.charAt(i) == 'o') {
lineInt |= (1 << i);
}
}
for (int i = 0; i < maxDigits; i++) {
posSol[i] = -1;
}
System.out.println(calculateLeastPebbles(lineInt));
}
}
private static int calculateLeastPebbles(int lineInt) {
if (posSol[lineInt] != -1) {
return posSol[lineInt];
}
int counter = 0;
for (int i = 0; i < 23; i++) {
if ((lineInt & (1 << i)) != 0) {
counter++;
}
}
for (int i = 0; i < 23; i++) {
if (i >= 2 && ((lineInt ^ (3 << (i - 2))) & (7 << (i - 2))) == 0) {
counter = Math.min(counter, calculateLeastPebbles(lineInt ^ (7 << (i - 2))));
}
if (i <= 20 && ((lineInt ^ (6 << i)) & (7 << i)) == 0) {
counter = Math.min(counter, calculateLeastPebbles(lineInt ^ (7 << i)));
}
}
return counter;
}
}
我可以做些什么来加快速度?