zoukankan      html  css  js  c++  java
  • LeetCode 39. Combination Sum

    题目

    暴力搜索

    struct Node
    {
        vector<int> a;
        int sum;
        int index;
        Node(){}
        Node(int index,int sum,vector<int> a)
        {
            this->index = index;
            this->sum = sum;
            this->a = a;
        }
        
    };
    
    class Solution {
    public:
        queue<Node> q;  
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            
            vector<vector<int>> ans;
            for(int i=0;i<candidates.size();i++)
            {
                vector<int> a;
                a.push_back(candidates[i]);
                q.push(Node(i,candidates[i],a));
            }
            
            while(!q.empty())
            {
                Node term = q.front();
                q.pop();
                
                if(term.sum==target)
                {
                    ans.push_back(term.a);
                    continue;
                }
                
                for(int i=term.index;i<candidates.size();i++)
                {
                    if(term.sum+candidates[i]>target)
                        continue;
                    else if(term.sum+candidates[i]==target)
                    {
                         vector<int> x = term.a;
                        x.push_back(candidates[i]);
                        ans.push_back(x);
                    }
                    else
                    {
                        vector<int> x = term.a;
                        x.push_back(candidates[i]);
                        q.push(Node(i,term.sum+candidates[i],x));
                    }
                }
            }
            return ans;
        }
    };
    
  • 相关阅读:
    函数之返回值
    函数之初识函数
    三元运算符
    枚举enumerate
    模块
    迭代器
    斐波那契
    leetcode155 最小栈
    leetcode94 二叉树的中序遍历
    leetcode20 有效的括号
  • 原文地址:https://www.cnblogs.com/dacc123/p/11304958.html
Copyright © 2011-2022 走看看