LeetCode:Combination Sum

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]

思路:
这个问题我看到就想到了找余下的值,也就是7-2=5,则找5在不在数组,不在就把2推进数组,然后5-2=3,找3,在的话就把3推进数组,然后就把这个小数组加入到大数组里,不过目前代码存在的问题是并不能找出所有解,只能找出部分,正在解决中orz。。。
目前出现的问题:
这里写图片描述

代码如下:
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>>res;
        int flag = 0;
        //bool is_add=false;
        //int count=candidates.size();
        for (int i = 0; i<candidates.size(); i++)
        {
            int temp = target;
            vector<int>m_vec;
            m_vec.push_back(candidates[i]);     
            while (temp>0)
            {
                if(target%candidates[i]==0&&target!=candidates[i])
                {
                    int count=target/candidates[i];
                    while(count!=1)
                    {
                        m_vec.push_back(candidates[i]);
                        count--;
                    }
                    res.push_back(m_vec);
                    break;
                }
                temp = temp - candidates[i];
                if (bfind(candidates, temp))
                {
                    m_vec.push_back(temp);
                    temp = 0;
                    res.push_back(m_vec);
                    break;
                }
                if (temp == 0)
                {
                    res.push_back(m_vec);
                    break;
                }
                m_vec.push_back(candidates[i]);
            }
        //j++;
        }
        return res;
}

    bool bfind(vector<int>& candidates, int target)//二分查找
    {
        vector<int>test(candidates);
        sort(test.begin(), test.end());
        int div = (test.size()-1) / 2;
        while (test[div] != target)
        {
            if (test[div]>target)
                div = (div-1)/2;
            else
                div = (test.size() + div ) / 2   ;
            if (test[div] == target)
                return true;
            else if (div == 0 && test[div] != target)
                return false;
            else if (div == test.size() - 1 && test[div] != target)
                return false;
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值