1 ms and easy understand Java solution.


  • 0
    A
    public class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> res = new ArrayList<>();
            List<Integer> temp = new ArrayList<>();
            
            find (res, temp, 1, k , n);
            return res;
        }
        
        public void find(List<List<Integer>> res, List<Integer> list, int begin, int k, int n) {
            if (k == 1) {
                if (n <= 9 && n >= 1) {
                    list.add(n);
                    List<Integer> temp = new ArrayList<>(list);
                    res.add(temp);
                    list.remove(list.size() - 1);
                }
                return;
            }
            
            for (int i = begin; i <= 9; i++) {
                if (n - i >= i + 1) {
                    list.add(i);
                    find (res, list, i + 1, k - 1, n - i);
                    list.remove(list.size() - 1);
                } else {
                    return;
                }
            }
        }
    }

Log in to reply
 

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