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

加起来和为目标值的组合(二)

http://www.nowcoder.com/practice/75e6cd5b85ab41c6a7c43359a74e869a

 * 
 * @param num int整型一维数组 
 * @param target int整型 
 * @return int整型二维数组
 */
function combinationSum2( num ,  target ) {
    // write code here
    if(num.length === 0)    return [];
    num.sort(function(a,b){return a - b});    //排序
    if(num.start > num)    return [];
    let res = [],tmp = [];
    dfs(num,target,res,tmp,0);
    return res;
}
function dfs(num,target,res,tmp,start){
    if(target === 0){
        res.push(tmp.slice());//提取数组所有元素(浅拷贝)
        return;
    }
    for(let i = start;i < num.length;i++){
        if(target < num[i])    break;
        if(i > start && num[i] === num[i - 1])    continue;    //去重
        tmp.push(num[i]);
        dfs(num,target - num[i],res,tmp,i + 1);
        tmp.pop();
    }
}
module.exports = {
    combinationSum2 : combinationSum2
};

alt

全部评论

相关推荐

07-02 10:44
门头沟学院 C++
码农索隆:太实诚了,告诉hr,你能实习至少6个月
点赞 评论 收藏
分享
每晚夜里独自颤抖:你cet6就cet6,cet4就cet4,你写个cet证书等是什么意思。专业技能快赶上项目行数,你做的这2个项目哪里能提现你有这么多技能呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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