How to realize the combination Sum in LeetCode
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!