search

Home  >  Q&A  >  body text

c++ - 算法题:N个数中找M个数,其之和等于target

LeetCode 上有一道M=2的题.
用两层循环遍历,O(n^2)可解。

但如果M=5M=10呢,在这种情况下,除了盲搜外,有什么想对高效的方法吗?

PHPzPHPz2773 days ago449

reply all(3)I'll reply

  • 阿神

    阿神2017-04-17 14:48:40

    Convert the problem into a 2 sum problem step by step.
    According to this idea, the complexity that k sum can achieve is $$ O(n^{k-1}). $$

    In addition, 2 sum can actually do $$ O(n) $$

    reply
    0
  • 黄舟

    黄舟2017-04-17 14:48:40

    After leetcode, there will be 4sum, 3sum questions, or 4sum converted to 3sum, 3sum to 2sum, after looking at the discussion forum, this idea is reliable

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:48:40

    Isn’t it converted into two arrays, traversing one and dividing the other into two?
    For example, m=7, traverse a 3n array, and then bisect another 4n array?
    n^((m+1)/2)

    reply
    0
  • Cancelreply