leetcode-pp / 91alg-14-daily-check

0 stars 0 forks source link

【Day 81 】2024-11-03 - 40 组合总数 II #87

Open azl397985856 opened 1 month ago

azl397985856 commented 1 month ago

40 组合总数 II

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/combination-sum-ii/

前置知识

candidates 中的每个数字在每个组合中只能使用一次。

说明:

所有数字(包括目标数)都是正整数。 解集不能包含重复的组合。 示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8, 所求解集为: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] 示例 2:

输入: candidates = [2,5,2,1,2], target = 5, 所求解集为: [ [1,2,2], [5] ]

Fightforcoding commented 1 month ago

class Solution: # T: O(nlogn + 2^n) S: O(n* 2^n) def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:

    candidates.sort()

    res = []
    def dfs(i, total, path):
        if total == target:
            res.append(path[:])
            return
        if total > target:
            return

        for j in range(i, len(candidates)):
            if j - 1 >= i and candidates[j] == candidates[j-1]:
                continue
            if candidates[j] > target:
                break
            dfs(j+1, total+candidates[j], path+[candidates[j]])

    dfs(0, 0, [])
    return res
sleepydog25 commented 1 month ago
class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates); // Sort to handle duplicates
        backtrack(result, new ArrayList<>(), candidates, target, 0);
        return result;
    }

    private void backtrack(List<List<Integer>> result, List<Integer> path, int[] candidates, int remaining, int start) {
        if (remaining == 0) {
            result.add(new ArrayList<>(path)); 
            return;
        }
        if (remaining < 0)
            return; 

        for (int i = start; i < candidates.length; i++) {
            // Skip duplicates
            if (i > start && candidates[i] == candidates[i - 1])
                continue;
            path.add(candidates[i]);
            backtrack(result, path, candidates, remaining - candidates[i], i + 1); // Move to next number
            path.remove(path.size() - 1); // Backtrack

        }
    }
}