zoukankan      html  css  js  c++  java
  • Leetcode40. Combination Sum组合总数2 II

    给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

    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] ]

    相比组合种数这道题加了个新加了去重操作,即递归了一个数后,回溯到此层时,把数组之后和该数相同的给过滤掉,防止出现重复的答案。

    bool cmp1(int x, int y)
    {
        return x < y;
    }
    
    class Solution {
    public:
        vector<vector<int> > res;
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target)
        {
            int len = candidates.size();
            sort(candidates.begin(), candidates.end(), cmp1);
            vector<int> temp;
            DFS(candidates, target, temp, 0);
            return res;
        }
    
        void DFS(vector<int> candidates, int val, vector<int> &v, int cnt)
        {
            if(val == 0)
            {
                res.push_back(v);
                return;
            }
            for(int i = cnt; i < candidates.size(); i++)
            {
                if(candidates[i] <= val)
                {
                    v.push_back(candidates[i]);
                    DFS(candidates, val - candidates[i], v, i + 1);
                    v.pop_back();
                    for(; i < candidates.size() - 1; i++)
                    {
                        if(candidates[i] == candidates[i + 1])
                            continue;
                        else
                            break;
                    }
                }
            }
        }
    };
  • 相关阅读:
    Construct Binary Tree From Inorder and Postorder Traversal
    Construct Binary Tree From Preorder and Inorder Traversal **
    Populating Next Right Pointers in Each Node II
    Populating Next Right Pointers in Each Node
    Flatten Binary Tree to Linked List
    E1总结和CISCO E1配置
    Dial-peer匹配顺序
    CUCM来实现PLAR
    CUCM实现Extension Mobility
    语音笔记20 URI
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433875.html
Copyright © 2011-2022 走看看