Concise java solution with a stack


  • 1
    C
    public class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> res = new ArrayList<>();
            helper(res, new Stack<Integer>(), n, 1, k);
            return res;
        }
        
        private void helper(List<List<Integer>> res, Stack<Integer> trace, int n, int start, int k) {
            if (k == 0) {
                res.add(new ArrayList<>(trace));
            } else {
                for (int i = start; i <= n - k + 1; ++i) {
                    trace.push(i);
                    helper(res, trace, n, i + 1, k - 1);
                    trace.pop();
                }
            }
        }
    }

Log in to reply
 

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