In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to achieve the combination sum in LeetCode, which is very detailed and has a certain reference value. Friends who are interested must read it!
Topic description
Find out the combination of all k numbers that add up to n. Only positive integers containing 1-9 are allowed in combinations, and there are no duplicate numbers in each combination.
Description:
All numbers are positive integers.
The solution set cannot contain duplicate combinations.
Example 1:
Input: K = 3, n = 7 output: [[1, 2, 4]]
Example 2:
Input: K = 3, n = 9 output: [[1Jing 2jue 6], [1Med 3JEI 5], [2Jing 3JEI 4]]
-A witty line of thinking-
-A witty line of thinking-
-A witty line of thinking-
The idea of solving the problem
Tags: recursive backtracking
Recursive termination condition: the array contains the number of k. If the sum is n, the result set is added, otherwise the termination recursion is returned directly.
Recursive process: loop through 1-9, add the new number to the temporary array, enter the next level of recursion, and then remove it
The key to backtracking is to add and remove, to ensure that all possibilities are traversed, and the overall structure is similar to the stack.
Backtracking procedure code class Solution {private List ans = new ArrayList (); public List combinationSum3 (int k, int n) {traceBack (k, n, 0,1, new LinkedList ()); return ans } public void traceBack (int k, int n, int sum, int begin, LinkedList list) {if (k = = 0) {if (n = sum) ans.add (new ArrayList (list)); return;} for (int I = begin; I < 10; iTunes +) {list.add (I) TraceBack (k-1, n, sum + I, I + 1, list); list.removeLast ();} above are all the contents of the article "how to achieve Combinatorial Sum in LeetCode". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.