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.
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]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
1 Public classSolution {2 PublicList<list<integer>> combinationSum3 (intKintN) {3arraylist<list<integer>> ans =NewArraylist<list<integer>>();4arraylist<integer> tmp =NewArraylist<integer>();5 if(K < 1 | | n < 1)returnans;6Combinationdfs (ans, tmp, K, N, 1, 0);7 returnans;8 }9 Ten Public voidCombinationdfs (arraylist<list<integer>> ans, arraylist<integer> tmp,intKintNintLevelintsum) { One if(sum = = N && k = = 0){ AAns.add (NewArrayList (TMP)); - return; -}Else if(Sum > N | | k < 0){ the return; - } - for(inti = level; i<=9; i++){ - Tmp.add (i); +Combinationdfs (ans,tmp,k-1,n,i+1,sum+i); -Tmp.remove (Tmp.size ()-1); + } A } at}
216. Combination Sum III Java Solutions