返回介绍

Combination Sum II

发布于 2025-02-22 13:01:31 字数 2719 浏览 0 评论 0 收藏 0

Source

Given a collection of candidate numbers (C) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.

Have you met this question in a real interview? Yes
Example
For example, given candidate set 10,1,6,7,2,1,5 and target 8,

A solution set is:

[1,7]

[1,2,5]

[2,6]

[1,1,6]

Note
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order.
(ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.

题解

Unique Subsets 非常类似。在 Combination Sum 的基础上改改就好了。

Java

public class Solution {
  /**
   * @param num: Given the candidate numbers
   * @param target: Given the target number
   * @return: All the combinations that sum to target
   */
  public List<List<Integer>> combinationSum2(int[] num, int target) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    List<Integer> list = new ArrayList<Integer>();
    if (num == null) return result;

    Arrays.sort(num);
    helper(num, 0, target, list, result);

    return result;
  }

  private void helper(int[] nums, int pos, int gap,
            List<Integer> list, List<List<Integer>> result) {

    if (gap == 0) {
      result.add(new ArrayList<Integer>(list));
      return;
    }

    for (int i = pos; i < nums.length; i++) {
      // ensure only the first same num is chosen, remove duplicate list
      if (i != pos && nums[i] == nums[i - 1]) {
        continue;
      }
      // cut invalid num
      if (gap < nums[i]) {
        return;
      }
      list.add(nums[i]);
      // i + 1 ==> only be used once
      helper(nums, i + 1, gap - nums[i], list, result);
      list.remove(list.size() - 1);
    }
  }
}

源码分析

这里去重的方法继承了 Unique Subsets 中的做法,当然也可以新建一变量 prev ,由于这里每个数最多只能使用一次,故递归时索引变量传 i + 1 .

复杂度分析

时间复杂度 O(n)O(n)O(n), 空间复杂度 O(n)O(n)O(n).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文