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]
Problem Solving Ideas:
A little lazy, directly on the Java for Leetcode 040 combination Sum II plus a depth, Java implementation is as follows:
Public list<list<integer>> combinationSum3 (int k, int n) {int[] candidates = {1, 2, 3, 4, 5, 6, 7, 8, 9}; arraylist<list<integer>> List = new arraylist<list<integer>> (); if (K > 9 | | | n > | | n/k = = 0) return List;dfs (list, candidates, 0, N, 0, K, 0); return list;} static list<integer> List2 = new arraylist<integer> (); static void Dfs (arraylist<list<integer> > list, int[] array, int result,int target, int depth, int k, int depth2) {if (result = = Target && depth2 = = k) {List.add (new arraylist<integer> (List2)); return;} else if (depth2 >= k | | result > Target | | depth >= array.length) return;for (int i = 0; I <= 1; i++) {for (int j = 0; J < I; J + +) {List2.add (array[depth]);d epth2++;} DFS (list, array, result + array[depth] * I, target, depth + 1, k,depth2); for (int j = 0; J < i; J + +) {List2.remove (list 2.size ()-1);d epth2--;}}}
Java for Leetcode 216 combination Sum III