leetcode 39. Combination Sum

本文详细解析了LeetCode中一道经典题目“组合求和”的解决方案,通过递归算法实现,探讨了如何避免重复组合的方法,并给出了清晰的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

“C++程序员觉得内存管理太重要了,所以一定要自己进行管理;Java/C#程序员觉得内存管理太重要了,所以一定不能自己去管理。”
简直人生态度。
Given a set of candidate numbers (C) 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]
]
candidate numbers (C):候选者数字集合
target:目标和
每个候选数字可使用多次 既然这样原集合重不重复就不重要了 用个set就可以了
刷leetcode之后 我发现学会的很重要的一件事:第一念头不是怎么解决问题,而是怎么把大问题转化成小问题,所有,我是说几乎所有,都可以用分治法,比如这道:
这里写图片描述
非常好 画了十分钟的图
画的过程中思路就会很清晰:

set排序:
递归方法:
        如果target == 0 有解 结束 当前解存入solution set里面
        否则:
            如果 最小候选数字 < target 无解 结束
            否则:
                遍历小于target的候选者 去做子问题的递归 

贴一个超时的代码:

Stack<Integer> result = new Stack<Integer>();
    Set<Stack<Integer>> results = new HashSet<Stack<Integer>>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> listResults = new ArrayList<List<Integer>>();
        Set<List<Integer>> setResults = new HashSet<List<Integer>>();
        Arrays.sort(candidates);
        backTracking(candidates, target);
        for(Stack<Integer> stackResult: results){
            List<Integer> listResult = stackResult.subList(0, stackResult.size());
            listResult.sort((a,b)->a-b);
            setResults.add(listResult);
        }
        setResults.forEach(a->listResults.add(a));
        return listResults;
    }

    public void  backTracking(int[] candidates,int target){
        if(target == 0) {
            Stack<Integer> copy = new Stack<Integer>();
            copy.addAll(result);
            results.add(copy);
        }
        else{
            if(candidates[0] > target)
                return ;
            else{
                for(int i = 0;i < candidates.length && candidates[0] <= target;i++){
                    result.push(candidates[i]);
                    backTracking(candidates, target-candidates[i]);
                    result.pop();
                }
            }
        }
    }

分析一下原因:嗯 图里面232 和 223确实是一种拿法却算了两次
我觉得我应该回去找找皇后那道题做一下 好菜。。
为了避免这种重复 本来我的代码是不避免的 所以232 223都返回 然后再stack 转 list list再sort 再判重复。。。果然前期不想好后期好麻烦。。。
前期如果避免232 223的这种重复:
记录开始位置 23后面只尝试3及3以上的 也就是:回溯的时候记录当前结果路径最大值对应原排序数组的位置 只从该位置开始尝试

    Stack<Integer> result = new Stack<Integer>();
    List<List<Integer>> results = new ArrayList<List<Integer>>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backTracking(candidates, target,0);
        return results;
    }

    public void  backTracking(int[] candidates,int target,int from){
        if(target == 0) {
            List<Integer> copy = new ArrayList<Integer>();
            copy.addAll(result);
            results.add(copy);
        }
        else{
            if(candidates[0] > target)
                return ;
            else{
                for(int i = from;i < candidates.length && candidates[0] <= target;i++){
                    result.push(candidates[i]);
                    backTracking(candidates,target-candidates[i],i);
                    result.pop();
                }
            }
        }
    }

终于写出了清楚的代码。。真的好菜。。。

1. Two Sum 2. Add Two Numbers 3. Longest Substring Without Repeating Characters 4. Median of Two Sorted Arrays 5. Longest Palindromic Substring 6. ZigZag Conversion 7. Reverse Integer 8. String to Integer (atoi) 9. Palindrome Number 10. Regular Expression Matching 11. Container With Most Water 12. Integer to Roman 13. Roman to Integer 14. Longest Common Prefix 15. 3Sum 16. 3Sum Closest 17. Letter Combinations of a Phone Number 18. 4Sum 19. Remove Nth Node From End of List 20. Valid Parentheses 21. Merge Two Sorted Lists 22. Generate Parentheses 23. Swap Nodes in Pairs 24. Reverse Nodes in k-Group 25. Remove Duplicates from Sorted Array 26. Remove Element 27. Implement strStr() 28. Divide Two Integers 29. Substring with Concatenation of All Words 30. Next Permutation 31. Longest Valid Parentheses 32. Search in Rotated Sorted Array 33. Search for a Range 34. Find First and Last Position of Element in Sorted Array 35. Valid Sudoku 36. Sudoku Solver 37. Count and Say 38. Combination Sum 39. Combination Sum II 40. First Missing Positive 41. Trapping Rain Water 42. Jump Game 43. Merge Intervals 44. Insert Interval 45. Unique Paths 46. Minimum Path Sum 47. Climbing Stairs 48. Permutations 49. Permutations II 50. Rotate Image 51. Group Anagrams 52. Pow(x, n) 53. Maximum Subarray 54. Spiral Matrix 55. Jump Game II 56. Merge k Sorted Lists 57. Insertion Sort List 58. Sort List 59. Largest Rectangle in Histogram 60. Valid Number 61. Word Search 62. Minimum Window Substring 63. Unique Binary Search Trees 64. Unique Binary Search Trees II 65. Interleaving String 66. Maximum Product Subarray 67. Binary Tree Inorder Traversal 68. Binary Tree Preorder Traversal 69. Binary Tree Postorder Traversal 70. Flatten Binary Tree to Linked List 71. Construct Binary Tree from Preorder and Inorder Traversal 72. Construct Binary Tree from Inorder and Postorder Traversal 73. Binary Tree Level Order Traversal 74. Binary Tree Zigzag Level Order Traversal 75. Convert Sorted Array to Binary Search Tree 76. Convert Sorted List to Binary Search Tree 77. Recover Binary Search Tree 78. Sum Root to Leaf Numbers 79. Path Sum 80. Path Sum II 81. Binary Tree Maximum Path Sum 82. Populating Next Right Pointers in Each Node 83. Populating Next Right Pointers in Each Node II 84. Reverse Linked List 85. Reverse Linked List II 86. Partition List 87. Rotate List 88. Remove Duplicates from Sorted List 89. Remove Duplicates from Sorted List II 90. Intersection of Two Linked Lists 91. Linked List Cycle 92. Linked List Cycle II 93. Reorder List 94. Binary Tree Upside Down 95. Binary Tree Right Side View 96. Palindrome Linked List 97. Convert Binary Search Tree to Sorted Doubly Linked List 98. Lowest Common Ancestor of a Binary Tree 99. Lowest Common Ancestor of a Binary Search Tree 100. Binary Tree Level Order Traversal II
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值