Find all possible combinations of K numbers This add up to a number n, given this only numbers from 1 to 9 can is 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]
Public classSolution {List<List<Integer>>Res; List<Integer>seq; PublicList<list<integer>> combinationSum3 (intKintN) {//dfs,for loops and recursive overlays. //The level value needs to be saved because the result requirement is incremented, and in order to ensure that it is the number of K, each recursion, K minus oneres=NewArraylist<list<integer>>(); Seq=NewArraylist<integer>(); DFS (K,n,1,0); returnRes; } Public voidDfsintKintNintStartintsum) { if(sum==n&&k==0) {Res.add (NewArraylist<integer>(seq)); }Else if(sum>n| | k<=0)return; for(inti=start;i<=9;i++) {seq.add (i); DFS (k-1,n,i+1,sum+i); Seq.remove (Seq.size ()-1); } }}
[Leedcode 216] combination Sum III