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

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

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

全部评论

相关推荐

06-12 16:00
天津大学 Java
牛客30236098...:腾讯坏事做尽,终面挂是最破防的 上次被挂了后我连简历都不刷了
点赞 评论 收藏
分享
07-02 13:52
武汉大学 golang
骗你的不露头也秒
牛客87776816...:😃查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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