zoukankan      html  css  js  c++  java
  • LeetCode CombinationSum

    class Solution {
    public:
        vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
            
            sort(candidates.begin(), candidates.end());
            candidates.erase(unique(candidates.begin(), candidates.end()), candidates.end());
            
            vector<vector<int> > tmp;
            vector<int> sel;
            
            dfs(candidates, 0, target, sel, tmp);
            return tmp;
        }
        
        void dfs(vector<int>& nums, int pos, int tar, vector<int>& sel, vector<vector<int> >& res) {
            if (tar == 0) {
                res.push_back(sel);
                return;
            }
            if (pos >= nums.size()) return;
            int cur = nums[pos];
            int add = 0;
            for (add = 0; add <= tar; add+=cur) {
                if (add != 0) {
                    sel.push_back(cur);
                }
                dfs(nums, pos + 1, tar - add, sel, res);
            }
            for (int i = add/cur - 1; i>0; i--) {
                sel.pop_back();
            }
        }
    };

    dfs搜索,通过unique操作去除重复的候选数字,避免产生重复的序列

  • 相关阅读:
    Nginx
    Haproxy
    Magento学习笔记2 createEntityType方法失效!
    PHP手册阅读笔记
    转载数据库设计
    PHP文件操作函数
    Magento学习笔记1
    PHP手册阅读笔记2
    C++疑惑
    定时任务quartz源码
  • 原文地址:https://www.cnblogs.com/lailailai/p/3606011.html
Copyright © 2011-2022 走看看