题解 | #加起来和为目标值的组合#

加起来和为目标值的组合

http://www.nowcoder.com/practice/172e6420abf84c11840ed6b36a48f8cd

先对数组进行排序,排序之后进行回溯思路来搜索;

因为元素可以重复,说明每次搜索可以从当前点开始搜索;

class Solution {
private:
    vector<vector<int>> res;
    vector<int> path;
    int cur_tar = 0;
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param target int整型 
     * @param nums int整型vector 
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > combinationCount(int target, vector<int>& nums) {
        // write code here
        sort(nums.begin(), nums.end());
        dfs(nums, target, 0);
        return res;
    }
    
    void dfs(vector<int>& nums, int target, int cur_i){
        if(cur_tar > target){
            return;
        }
        
        if(cur_tar == target){
            res.push_back(path);
            return;
        }
        
        for(int i=cur_i; i<nums.size(); i++){
            cur_tar += nums[i];
            path.push_back(nums[i]);
            dfs(nums, target, i);
            cur_tar -= nums[i];
            path.pop_back();
        }
    }
    
};
全部评论

相关推荐

昨天 13:43
门头沟学院 Java
longerluck...:我猜说的是“你真**是个天才”
投递美团等公司10个岗位
点赞 评论 收藏
分享
程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
牛客刘北:如果暑期实习是27届的话,你要晚一年才会毕业,企业为什么会等你呢?要搞清时间逻辑呀!27届现在实习只能是在暑假实习,这是日常实习,不是暑期实习。所以多去投日常实习吧,暑期实习肯定不会要你的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务