问题陈述::在Java中,给定一个int数组,是否可以选择一组int值,从而使得该组与给定的目标相加,并附加这个约束:如果存在数组中相邻且相同值的数字,它们必须全选或全选。例如,对于数组{1,2,2,2,5,2},中间的所有三个2必须被选择或不被选择,全部作为一个组。 (一个循环可用于查找相同值的范围)。Java算法问题
groupSumClump(0, {2, 4, 8}, 10) → true
groupSumClump(0, {1, 2, 4, 8, 1}, 14) → true
groupSumClump(0, {2, 4, 4, 8}, 14) → false --> Failing Test Case
groupSumClump(0, {8, 2, 2, 1}, 9) → true --> Failing Test Case
groupSumClump(0, {8, 2, 2, 1}, 11) → false --> NegativeArraySizeException
我已经做了一些初步分析,部分代码如下。
public boolean groupSumClump(int start, int[] nums, int target) {
start = 0;
boolean flag = false;
// get the highest int from the list of array we have
int highestInteger = getTheBiggest(nums);
if (highestInteger > target) {
flag = false;
} else {
int variable = 0;
for (int i = 0; i < nums.length; i++) {
variable += nums[i];
}
if (variable == target) {
flag = true;
} else {
if (variable < target) {
flag = false;
} else {
// here goes ur grouping logic here
flag = summate(highestInteger, target, nums);
}
}
}
return flag;
}
private boolean summate(int highestInteger, int target, int[] nums) {
boolean val = false;
if (highestInteger == target) {
val = true;
} else {
int[] temp = new int[nums.length - 1];
int var = 0;
if ((target - highestInteger) > 0) {
for (int j = 0; j < nums.length-1; j++) {
if (nums[j] != highestInteger) {
temp[var] = nums[j];
if (temp[var] == (target - highestInteger)) {
val = true;
return val;
}
var++;
}
}
val = summate(getTheBiggest(temp), target - highestInteger,
temp);
}
}
return val;
}
private int getTheBiggest(int[] nums) {
int biggestInteger = 0;
for (int i = 0; i < nums.length; i++) {
if (biggestInteger < nums[i]) {
biggestInteger = nums[i];
}
}
return biggestInteger;
}
请注意:我不知道如何处理以下问题陈述的逻辑: 有一个Additional Constraint
的问题,例如,如果有数组在相邻和相同价值的数字,他们必须要么全部选择,要么没有选择。例如,对于数组{1,2,2,2,5,2},中间的所有三个2必须被选择或不被选择,全部作为一个组。 (一个循环可用于查找相同值的范围)。
我应该如何处理上述问题中的这部分逻辑。 我一直在努力争取这个权利,不知道。 提供的建议将不胜感激。 你让我知道什么是代码问题/如何处理这个问题的附加约束: - ((
其他约束说,你选择作为一个组,而不是选择作为一个group.so我不知道如何proceed.if u能请帮me.it可以理解
编辑USER-> MISSINGNO:我已经添加了下面的代码结构,以上述主要代码,并打印我的错values.where我错了
groupSumClump(0,{2,4,4,8},14)→false再次失败该标志是 - > true,这是错误的。
for(int number=0;number<nums.length-1;number++){
if(nums[number]==nums[number+1]){
nums[number]=nums[number]+nums[number+1];
}
}
这也是我回答了 - 你:) – extraneon 2011-05-15 14:20:37
刚过什么是我需要的代码改变now.i中号无法继续。 – 2011-05-15 14:20:54
我很肯定你可以从现在开始做这件事。我们在这里没有给出家庭作业问题的代码。 – hugomg 2011-05-15 14:25:42