Share my recursive JAVA solution


  • 0
    W
    public class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if (k == 0 || n == 0) return res;
            dfs(res, new ArrayList<Integer>(), 1, k, n);
            return res;
        }
        private void dfs(List<List<Integer>> res, List<Integer> list, int start, int k, int n) {
            if (k == 0) {
                if (n == 0) res.add(new ArrayList<Integer>(list));
                return;
            }
            for (int i = start; i <= 9; i++) {
                list.add(i);
                dfs(res, list, i + 1, k - 1, n - i);
                list.remove(list.size() - 1);
            }
        }
    }

Log in to reply
 

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