7 lines recursive solution, 3ms


  • 0
    public class Solution {
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        public List<List<Integer>> combinationSum3(int k, int n) {
            helper(new ArrayList<>(),k,n,0);
            return res;
        }
        private void helper(List<Integer> list, int k, int n, int i) {
    		for(int j = i+1; j < 10; j++){
    			List<Integer> l = new ArrayList<>(list);
    			l.add(j);
    			if(k == 1 && n - j == 0)res.add(l);
    			if(n > j && k > 1) helper(l,k-1,n-j,j);
    		}
    	}
    }
    

Log in to reply
 

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