• Leetcode39.Combination Sum组合总和


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

    candidates 中的数字可以无限制重复被选取。

    说明:

    • 所有数字(包括 target)都是正整数。
    • 解集不能包含重复的组合。 

    示例 1:

    输入: candidates = [2,3,6,7], target = 7, 所求解集为: [ [7], [2,2,3] ]

    示例 2:

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

    先排序,后剪枝,避免重复。

    这类问题解决重复的操作一般是先进行排序。

    bool cmp1(int x, int y)
    {
        return x < y;
    }
    
    class Solution {
    public:
        vector<vector<int> > res;
        vector<vector<int> > combinationSum(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);
                    v.pop_back();
                }
            }
        }
    };

  • 相关阅读:
    刷题238. Product of Array Except Self
    刷题236. Lowest Common Ancestor of a Binary Tree
    刷题208. Implement Trie (Prefix Tree)
    A1070
    A1048
    A1050
    A1041
    A1092
    A1084
    n进制转十进制
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433878.html
Copyright © 2020-2023  润新知