zoukankan      html  css  js  c++  java
  • Leetcode: 40. Combination Sum II

    Description

    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.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    Example

    For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, 
    A solution set is: 
    [
        [1, 7],
        [1, 2, 5],
        [2, 6],
        [1, 1, 6]
    ]
    

    思路

    • dfs
    • 由于每个数字只可以用一次,所以进入递归的下一个起点应该是当前位置的下个位置
    • 注意可能出现重复情况

    代码

    class Solution {
    public:
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            vector<vector<int>> res;
            vector<int> tmp;
            
            sort(candidates.begin(), candidates.end());
            dfs(candidates, target, candidates.size(), 0, res, tmp, 0);
            
            return res;
        }
        
        bool dfs(vector<int>& candidates, int target, int len, int t, vector<vector<int>> &res,
                vector<int>& tmp, int sum){
            if(sum == target){
                res.push_back(tmp);
                return true;
            }
            else if(sum < target){
                bool flag = false;
                for(int i = t; i < len; ++i){
                    //考虑当前元素同前一个是重复的情况
                    if(i > t && candidates[i] == candidates[i - 1]) continue;
                    if(sum + candidates[i] > target)
                        return false;
                        
                    sum += candidates[i];
                    tmp.push_back(candidates[i]);
                    
                    //从i+1位置进入下一层递归
                    flag = dfs(candidates, target, len, i + 1, res, tmp, sum);
                    sum -= candidates[i];
                    tmp.pop_back();
                    if(flag)
                        break;
                }
            }
            
            return false;
        }
    };
    
  • 相关阅读:
    避免前置声明
    CLion在WSL上远程调试代码设置
    push_back与构造函数
    _BLOCK_TYPE_IS_VALID(pHead->nBlockUse问题解析
    Qt报错
    关于引用与指针实现多态的一些记录
    Vue-Axios异步通信
    Kafka概述
    学习Ajax看着一篇就够了
    学习Json看着一篇就够了
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6841823.html
Copyright © 2011-2022 走看看