【问题标题】:Find number x equal to sum of 1 number from n sets从 n 个集合中找到等于 1 个数字之和的数字 x
【发布时间】:2021-12-28 22:37:45
【问题描述】:

我遇到以下问题:

我有 n 个已排序的整数集合 (2 我有一个数字 x。
我想知道是否有一个总和(可以有多个),其中每组需要恰好贡献1个数字,等于x

示例 1:
集合 1:{1、2、3、5、7、8}
集合 2:{2, 4, 4, 5, 6, 8, 9, 11 23}
x: 9
对于此示例,可能的总和为 5+4。另一种可能是1+8。

示例 2:
集合 1:{1、1、5、7、8、9}
集合 2:{2、4、5、6、8、9}
x: 8
在此示例中,没有可能的总和。数字 8 在两个集合中都有,但由于所有集合都需要在总和中做出贡献,所以这无关紧要。


我不想强行这样做,所以我认为递归可以使这个过程更快一点,但我真的不知道从哪里开始。 我正在寻找某种思路,尽管伪代码或工作代码(java)将不胜感激:)

【问题讨论】:

  • 递归不是为了优化性能。这是关于逻辑简化。
  • 遍历第一个集合,确定其他集合是否可以提供剩余部分。可以记住答案(在每个后续集合中),以便下次需要检查该值时,答案就已经知道了。
  • 你想要什么样的结果?一个布尔值,是否存在这样的总和或所有可能组合的数量或所有可能组合的列表
  • 布尔值就可以了

标签: java recursion


【解决方案1】:

试试这个。

static boolean existSum(List<Collection<Integer>> collections, int x) {
    int size = collections.size();
    return new Object() {
        boolean find(int index, int sum) {
            if (index >= size)
                return sum == x;
            for (int i : collections.get(index)) {
                int newSum = sum + i;
                if (newSum > x)
                    break;
                if (find(index + 1, newSum))
                    return true;
            }
            return false;
        }
    }.find(0, 0);
}

public static void main(String[] args) throws Exception {
    System.out.println(existSum(List.of(
        List.of(1, 2, 3, 5, 7, 8),
        List.of(2, 4, 4, 5, 6, 8, 9, 11, 23)), 9));
    System.out.println(existSum(List.of(
        List.of(1, 1, 5, 7, 8, 9),
        List.of(2, 4, 5, 6, 8, 9)), 8));
}

输出:

true
false

【讨论】:

  • 当传入的集合数量大于两个时,此代码给出错误答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多