【问题标题】:Check recursively if possible to split an array into two arrays meeting certain criteria如果可能,递归检查将一个数组拆分为两个满足特定条件的数组
【发布时间】:2019-05-31 22:14:59
【问题描述】:

我正在解决来自CodingBat 的以下问题:

给定一个整数数组,是否可以将整数分成两组,使得一组的和是 10 的倍数,而另一组的和是奇数。每个 int 必须在一个组中。编写一个递归助手方法,它接受你喜欢的任何参数,并从 splitOdd10() 对你的递归助手进行初始调用。 (不需要循环。)

我发现a post on SO discussing a similar topic 是否可以将一个数组分成两个具有相等乘积的数组,并尝试通过类比编写代码。这是我目前得到的(在 Java 中):

public boolean splitOdd10(int[] nums) {
    if (nums.length == 0)
    return false;
  else
    return canSplit(0, nums, 0);
}

private boolean canSplit(int first, int[] nums, int term) {
    if (first == nums.length - 1)
    return (term + nums[first]) % 10 == 0 || (term + nums[first]) % 2 == 1;
  else
    return canSplit(first + 1, nums, term + nums[first]);
}

但是在进一步思考代码后,我了解到它只是检查整个原始数组的总和是 10 的倍数还是奇数。

我很难理解如何从 n 步进到 n-1 以及绑定条件应该是什么,因为这两个数组不相互依赖,这与它们的乘积相等时不同。

有人可以给我一个提示吗?谢谢。

【问题讨论】:

  • 不太确定这是否已在问题中得到澄清。但是一组中的任何一个都可以是空的吗?例如nums size 1 或者如果所有元素都可以满足一个条件,则将它们归为一组?
  • @nullpointer 我刚刚查了一下 - {1} 的预期答案是真的,所以是的,其中一个数组可能是空的。

标签: java arrays algorithm recursion


【解决方案1】:

假设您必须创建两个组(A 和 B)。对于每个元素,您有两个选择:可以将当前元素放入 A 组或 B 组。

状态:mod10(A组模块10中所有元素的总和),odd2(B组模块2中所有元素的总和)

bool check(int arr[], int idx, int mod10, int odd2,  int size){ 

  if(idx == size){

     return (mod10 == 0 and odd2 == 1);
}

   // include current element in group A

  bool first_choice = check(arr, idx + 1, (mod10 + arr[idx]) % 10, odd2, size)

   // include  current element in group B

  bool second_choice = check(arr, idx + 1, mod10, (odd2 + arr[idx]) % 2, size)

  return (first_choice or second_choice);    
}

您可以将这些状态保存在表格中,复杂度 O(size * 10 * 2) 其中 size = 数组中的总元素

【讨论】:

  • 为什么需要将 mods 传递给函数?
【解决方案2】:

将发布我自己的代码,我认为它更清晰一些(至少对我而言):

public boolean splitOdd10(int[] nums) {     
  if (nums.length == 0)
    return false;
  else
    return canSplit(0, nums, 0, 0);
}

private boolean canSplit(int index, int[] nums, int mod10Sum, int oddSum) {

  if (index == nums.length)
    return mod10Sum % 10 == 0 && oddSum % 2 == 1;
  else
    return canSplit(index + 1, nums, mod10Sum + nums[index], oddSum)
          || canSplit(index + 1, nums, mod10Sum, oddSum + nums[index]);
}

【讨论】:

    猜你喜欢
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多