Simple java solution


  • 1
    H
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        int[] can = {1,2,3,4,5,6,7,8,9};
        Arrays.sort(can);
        helper(can, 0, n, new ArrayList<Integer>(), k);
        return res;
    }
    
    private void helper(int[] can, int start, int target, List<Integer> each, int len) {
        if (each.size() >= len) {return;}
        for (int i = start; i < can.length; i++) {
            List<Integer> temp = new ArrayList<>(each);
            if (can[i] == target) {
                if (each.size() == len - 1) {
                    temp.add(can[i]);
                    res.add(temp);
                }
                break;
            } else if (can[i] < target) {
                temp.add(can[i]);
                helper(can, i+1, target-can[i], new ArrayList<>(temp),len);
            } else {break;}
        }
        return;
    }

  • 0
    L

    you really don't have to sort "can" since you created it sorted


  • 0
    D

    Why you point it out so directly, lol


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.