Simple java code - build only lists for results


  • 0
    B

    Code similar to others, but not creating new lists for EACH recursive call - but only generating a new list for when a result was found. Maybe this saves some space:

    public List<List<Integer>> combinationSum3(int k, int n) {
            return getCombination(k, n, 1);
        }
        
        List<List<Integer>> getCombination(int k, int n, int startNum) {
            List<List<Integer>> result = new ArrayList();
             
            // base case - if k == 1
            if (k == 1) {
                return (n < 10 && n > 1 && n >= startNum ? Arrays.asList(Arrays.asList(n)) : new ArrayList());
            }
            for (int i = startNum; i < 10; i++) {
                List<List<Integer>> tempList = getCombination(k - 1,  n - i, i + 1);
                for (List list : tempList) {
                   	List<Integer> l = new ArrayList();
                   	l.add(i);
                   	l.addAll(list);
                    result.add(l);
                }
            }
            return result;
        }
    

Log in to reply
 

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