LeetCode 39. Combination Sum

题目

暴力搜索

struct Node
{
    vector a;
    int sum;
    int index;
    Node(){}
    Node(int index,int sum,vector a)
    {
        this->index = index;
        this->sum = sum;
        this->a = a;
    }
    
};

class Solution {
public:
    queue q;  
    vector> combinationSum(vector& candidates, int target) {
        
        vector> ans;
        for(int i=0;i 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;itarget)
                    continue;
                else if(term.sum+candidates[i]==target)
                {
                     vector x = term.a;
                    x.push_back(candidates[i]);
                    ans.push_back(x);
                }
                else
                {
                    vector x = term.a;
                    x.push_back(candidates[i]);
                    q.push(Node(i,term.sum+candidates[i],x));
                }
            }
        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode 39. Combination Sum)