2 回答
TA贡献1757条经验 获得超7个赞
您应该从任何位置获取所有可能的数字。因此,为了获得所有可能的结果,您可以使用这些数字的排列来序列化这些数字。另一种方法是使用带递归的位掩码。这是您的问题的解决方案。(基于位掩码和递归)。
public static boolean isValidResult(ArrayList<Integer> score, int selectedPoints)
{
return canMakeValid(score, selectedPoints, 0, 0); // first 0 is for masking, second 0 is for summation.
}
public static boolean canMakeValid(ArrayList<Integer> score, int selectedPoints, int mask, int sum)
{
if(sum > selectedPoints) return false;
sum %= selectedPoints;
int sz = score.size();
if(mask == ((1<<sz)-1)) {
if(sum == 0) return true;
return false;
}
boolean ret = false;
for(int i = 0; i < sz; i++) {
if((mask&(1<<i)) == 0) {
ret = ret | canMakeValid(score, selectedPoints, mask | (1<<i), sum + score.get(i));
}
}
return ret;
}
您可以从此链接了解位掩码:https://discuss.codechef.com/t/a-small-tutorial-on-bitmasking/11811/3
TA贡献1827条经验 获得超8个赞
确实有一些递归解决方案。
public static boolean isValidResult(List<Integer> score, int selectedPoints) {
score.sort();
return isValidResultRec(score, selectedPoints, 0);
}
/**
* @param scoreI the first position to consider to add or not add.
*/
private static boolean isValidResultRec(List<Integer> score, int selectedPoints, int scoreI) {
while (!score.isEmpty() && scoreI < score.size()) {
int index = Collections.binarySearch(score, selectedPoints);
if (index >= 0) {
return true;
}
// Now ~index is the insert position;
// i >= ~index are values > selectedPoints.
score = score.subList(~index, score.size());
for (int i = scoreI; i < ~index; ++i) {
int value = score[i]; // value < selectedPoints.
score.remove(i); // Do step.
if (isValidResultRec(score, selectedPoints - value, scoreI + 1) {
return true;
}
score.add(i, value); // Undo step.
}
}
return false;
}
这里使用排序;使用递减顺序、Comparator.reversed()或 afor --i将采取更大的步骤。
递归应该添加或不添加第 i个骰子值。
这里的代码可以写得更好。
添加回答
举报
