zoukankan      html  css  js  c++  java
  • Leetcode 39

    using namespace std;
    typedef long long ll;
    typedef unsigned long long ull;
    typedef double db;
    typedef long double ld;
    
    #define REP(x, l, u) for(ll x = l;x<u;x++)
    #define RREP(x, l, u) for(ll x = l;x>=u;x--)
    #define se second
    #define fi first
    typedef vector<int> VI;
    typedef unordered_map<int,int> UMAPI;
    const ll mod = 1e9 + 7;
    #define len(x) x.size()
    
    class Solution {
        VI res;
        vector<VI> ans;
        int n;
        void search(VI& candidates, int target, int start){
            if (target == 0){
                ans.emplace_back(res);
                return;
            }
            for(int i = start; i < n; i++){
                if(target  - candidates[i] >= 0){
                    res.push_back(candidates[i]);
                    search(candidates, target - candidates[i], i);
                    res.pop_back();
                }
                else break;
            }
        }
        
    public:
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            n = len(candidates);
            sort(candidates.begin(), candidates.end());
            search(candidates, target, 0);
            return ans;
        }
    };

    普通回溯题,说是剪枝,其实算是贪心吧……所以需要事先排序

  • 相关阅读:
    C/C++一些库函数的实现
    约瑟夫环问题(Josephus)
    union关键字及大小端模式
    指针数组和数组指针
    巧用位运算
    C/C++生成可执行文件过程
    C语言+Modbus+NXP整体规划
    bug和待完善
    python学习第二课
    python学习第一课
  • 原文地址:https://www.cnblogs.com/KakagouLT/p/13638111.html
Copyright © 2011-2022 走看看