Simple Java solution


  • 0
    L
    public List<List<Integer>> combinationSum3(int k, int n) {
                List<List<Integer>> res = new ArrayList<List<Integer>>();
                int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
                getCombinationSum3(nums, 0, k, n,  res);
                
                return res;
            }
            
            void getCombinationSum3(int[] nums, int i, int count, int n, List<List<Integer>> res) {
                if (i >= 9 || count <= 0) return;
                int total = n - nums[i];
                
                if (count == 1) {
                    if (total == 0) { //found it.
                        List<Integer> l = new ArrayList<Integer>();
                        for (int j = 0; j <= i; j++){
                            if (nums[j] != 0) l.add(nums[j]);
                        }
                        res.add(l);
                    } else if (total < 0) return;
                }
                
                getCombinationSum3(nums, i + 1, count - 1, n - nums[i], res);
                
                nums[i] = 0;
                getCombinationSum3(nums, i + 1, count, n, res);
                nums[i] = i + 1;
            }
    

Log in to reply
 

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