I. Title Description
Find all possible combinations of k numbers this add up to a number n, given this only numbers from 1 to 9 can be used and Each combination should is a unique set of numbers.
Ensure that numbers within the set is sorted in ascending order.
Example 1:
Input:k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input:k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
Two. Topic analysis
This problem is a combination of the series and the third problem, with the previous two combination Sum combination of the first two questions of the link is relatively close, the change is not big, and this is the most significant difference is that the problem requires a solution of the number of elements of K.
In fact, the problem is combination sum and combination sum II of the complex, the two are mixed together is the solution of the problem. n is the sum of k numbers, if n<0, then directly return, if n = = 0, and at this time the temporary combination of the number of numbers in the temp is exactly k, indicating that at this time is a suitable combination of solutions, will be stored in the result results.
Three. Sample code
#include <iostream>#include <vector>using namespace STD;classSolution { Public: vector<vector<int> >COMBINATIONSUM3 (intKintN) { vector<vector<int> >Result vector<int>Temp Combinationsum3dfs (k, N,1, temp, result);returnResult }Private:voidCombinationsum3dfs (intKintNintLevel vector<int>&temp, vector<vector<int> >&result) {if(N <0)return;if(n = =0&& temp.size () = = k) result.push_back (temp); for(inti = level; I <=9; ++i) {temp.push_back (i); Combinationsum3dfs (k, n-i, i +1, temp, result); Temp.pop_back (); } }};
Four. Summary
The combination sum series is a classic Dfs topic that needs to be studied in depth.
Leetcode Note: Combination Sum III