Combination Sum III
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Ensure that numbers within the set are 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]]
Solution: Recursion.
Let combinationSum3(int k, int n, int i) denotes that we solve this problem using numbers from i to 9. Then all we need to do is to call combinationSum3(k, n, 1).
Let combinationSum3(int k, int n, int i) denotes that we solve this problem using numbers from i to 9. Then all we need to do is to call combinationSum3(k, n, 1).
public class Solution { private List<List<Integer>> combinationSum3(int k, int n, int i) { ArrayList<List<Integer>> list = new ArrayList<List<Integer>>(); if (i > 9 || k < 1 || n < i) { return list; } if (k == 1 && n == i) { ArrayList<Integer> l = new ArrayList<Integer>(); l.add(i); list.add(l); return list; } List<List<Integer>> l1 = combinationSum3(k, n, i + 1); list.addAll(l1); List<List<Integer>> l2 = combinationSum3(k - 1, n - i, i + 1); for (List<Integer> ll : l2) { ArrayList<Integer> l = new ArrayList<Integer>(); l.add(i); l.addAll(ll); list.add(l); } return list; } public List<List<Integer>> combinationSum3(int k, int n) { return combinationSum3(k, n, 1); } }
No comments:
Post a Comment