`
bcyy
  • 浏览: 1828397 次
文章分类
社区版块
存档分类
最新评论

Combination Sum -- LeetCode

 
阅读更多
原题链接:http://oj.leetcode.com/problems/combination-sum/

这个题是一个NP问题,方法仍然是N-Queens中介绍的套路。基本思路是先排好序,然后每次递归中把剩下的元素一一加到结果集合中,并且把目标减去加入的元素,然后把剩下元素(包括当前加入的元素)放到下一层递归中解决子问题。算法复杂度因为是NP问题,所以自然是指数量级的。代码如下:

public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    if(candidates == null || candidates.length==0)
        return res;
    Arrays.sort(candidates);
    helper(candidates,0,target,new ArrayList<Integer>(),res);
    return res;
}
private void helper(int[] candidates, int start, int target, ArrayList<Integer> item, 
ArrayList<ArrayList<Integer>> res)
{
    if(target<0)
        return;
    if(target==0)
    {
        res.add(new ArrayList<Integer>(item));
        return;
    }
    for(int i=start;i<candidates.length;i++)
    {
        if(i>0 && candidates[i]==candidates[i-1])
            continue;
        item.add(candidates[i]);
        helper(candidates,i,target-candidates[i],item,res);
        item.remove(item.size()-1);
    }
}
注意在实现中for循环中第一步有一个判断,那个是为了去除重复元素产生重复结果的影响,因为在这里每个数可以重复使用,所以重复的元素也就没有作用了,所以应该跳过那层递归。这道题有一个非常类似的题目Combination Sum II,有兴趣的朋友可以看看,一次搞定两个题哈。

分享到:
评论

相关推荐

    leetcode怎么销号-LeetCode-Solutions:我自己的LeetCode解决方案

    LeetCode-Solutions :green_heart:My own LeetCode solutions No. Problem LeetCode 力扣 Python Go Solution Difficulty Tag 0017 Letter Combinations of a Phone Number Medium 回溯、暴力 0034 Find First and ...

    數位之和leetcode-leetcode-cpp:我的LeetCodeC++答案

    LeetCode-cpp 个人 LeetCode C++ 答案库。 我的 LeetCode 个人资料: 如果你想讨论,请加入QQ群: 其他语言 优先级从高到低排列。 一句话总结问题 命名规则 number-this_is_title-difficulty (e-easy, m-medium, h-...

    leetcode296-leetcode-in-py-and-go:Go中的Leetcode

    第 296 章PY 和 GO 中的 Leetcode 我在 Python Golang ...Leetcode ...40:combination-sum-ii:传递最后选择的索引 41:先缺失正,交换 42:只是提醒:块 - 垃圾箱 43:多字符串,i+j,i+j+1 44:通配符

    leetcode怎么计算空间复杂度是指-LeetCode-Solution:我的第一个LeetCode解决方案

    LeetCode-Solution my first solution of LeetCode 2015-5-7 Problem 95,98(80 already!) 我经常在递归的结束地方忘记return!!! 题型一:经典暴力递归:(里面涉及到重复不重复的时候,需要注意该如何处理!) 模板...

    leetcode打不开-leetcode:leetcode

    leetcode打不开Leetcode Note Tips Tip1: Two pointer for sorted array (#Array 1. Two Sum) Tip2: Sum[i:j] = Sum[0:j] - Sum[0:i] for continuous array (# Array 560. Subarray Sum Equals K) Tip3: Knapsack ...

    leetcode316-leetcode_problems:LeetCode刷题记录

    Combination Sum Description 给一组candidates (list of int)和target (int),求使用candidates内数字组合,让总和等于target的所有组合。 candidates内的数字皆不同 candidates内的数字可以重复使用无限次 ...

    leetcode2sumc-Leetcode_imp_C:Leetcode在C上的实现

    leetcode 2 和 c Leetcode_imp_C Leetcode 在 C 上的实现 大批: leetcode_0001_two_sum.c leetcode_0011_max_area.c leetcode_0015_three_sum.c ...leetcode_0039_combination_sum.c 40 leetcode_0041_first_miss

    gasstationleetcode-Leetcode:力码

    Leetcode\combination sum(39).swift Leetcode\count number of team(1395).swift Leetcode\counting bits(338).swift Leetcode \find 数组中的所有重复项(442).swift Leetcode\find peak element(162).swift ...

    leetcode530-Leetcode:新的开始

    leetcode 530 力码 全部的: 易(173/237+x) 中(144/437+x) 硬(4/x) 问题 1.Two Sum(dict) 7.(跳过)(数学) 9.(跳过)(串串技巧) 11.盛水最多的容器 12.(跳过)(问题不好) 13.(跳过)(蛮力) 14.(跳过)...

    leetcode最大蓄水量-leetcode_note_book:leetcode题目分类及刷题总结

    CombinationSum 组合之和 完成 LinkedList 题目 说明 状态 AddTwoNumber 两数相加 完成 SwapPairs 两两交换链表中的节点 完成 String 题目 说明 状态 LongestSubstring 最长子串 完成 LongestPalindrome 最长回文...

    leetcode题库-little-algorithm:LeetCode题目参考代码与详细讲解,公众号《面向大象编程》文章整理

    leetcode题库 Little Algorithm 从 2020 年初开始,我在公众号《面向大象编程》上发表面试算法、LeetCode 题解相关文章,至今收获不少好评。此仓库是公众号内容的补充,包括公众号文章涉及到的题目的参考代码,以及 ...

    leetcode2-LeetcodeNotes:LeetCode解决方案和一切

    leetcode 2 Useful Links ...Sum], [17 Phone Num] [] BFS [] [] [] DP , [53 max subarray], , [96 DP | BST], , [] [] Binary Search , , [74 2D matrix] [] Slicing Window / Two Pointers [918 Ma

    Coding Interview In Java

    leetcode Java 246 題目及解答 (英文) Contents 1 Rotate Array in Java 15 2 Reverse Words in a String II 19 3 Evaluate Reverse Polish Notation 21 4 Isomorphic Strings 25 5 Word Ladder 27 6 Word Ladder ...

    leetcode2sumc-CTCI:CTCI

    combinationSum ( self , candidates , target ): def backtrack ( tmp , start , end , target ): if target == 0 : ans . append ( tmp [:]) elif target &gt; 0 : for i in range ( start , end ): tmp . append ( ...

    cpp-算法精粹

    Combination Sum III Generate Parentheses Sudoku Solver Word Search 总结 分治法 Pow(x,n) Sqrt(x) 贪心法 Jump Game Jump Game II Best Time to Buy and Sell Stock Best Time to Buy and Sell Stock II Longest...

    对python append 与浅拷贝的实例讲解

    def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ result,temp = [],[] self.combinationSumRecu(sorted(candidates),...

Global site tag (gtag.js) - Google Analytics