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]
Because it is limited to 1-9, it is easier to enumerate. Let the array of answers be arranged in ascending order and then put in the number on the inside.
Tips: Use arrays faster than with ArrayList.
Public classSolution { PublicList<list<integer>>list; PublicList<list<integer>> combinationSum3 (intKintN) {list=NewArrayList (); if(n > (18-k + 1) * K/2 | | n < (1 + k) * k/2 | | k > 9){ returnlist; } int[] Nums =New int[K]; for(inti = 1; I <= 10-k; i++) {nums[0] =i; Getsum (Nums, N,0, K-1); } returnlist; } Public voidGetsum (int[] ans,intNintPosintk) { if(k = = 0){ intsum = 0; for(inti = 0; i < ans.length; i++) {sum+=Ans[i]; } if(Sum = =N) {List<Integer> LL =NewArrayList (); for(intI:ans) {Ll.add (i); } list.add (LL); } return ; } for(inti = Ans[pos] + 1; I <= 10-k; i++) {Ans[pos+ 1] =i; Getsum (ans, N, pos+ 1, k-1); } } }
Leetcode 216. Combination Sum III Sum III----------Java