Add one more conditions

Time complexity

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        //validate input
        if (k == 0 || n < 1) return result;

        dfsHelper(result, new ArrayList<Integer>(), k, n, 1);

        return result;
    }

    private void dfsHelper(List<List<Integer>> result, List<Integer> list, int k, int n, int start) {
        //end conditions
        if (k == 0) {
            if (n == 0) {
                result.add(new ArrayList<>(list));
            }
            return;
        }

        for (int i = start; i <= 9; ++i) {
            if (list.contains(i)) continue;
            if (n >= i) {
                list.add(i);
                dfsHelper(result, list, k - 1, n - i, i + 1);
                list.remove(list.size() - 1);
            }
        }

    }
}

results matching ""

    No results matching ""