5ms Java Backtracking Solution Beats 94%


  • 0
    Z
    public class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> list = new ArrayList<>();
            backtrack(list, new ArrayList<Integer>(), 1, n, k);
            return list;
        }
        
        public void backtrack(List<List<Integer>> list, List<Integer> res, int start, int n, int k){
            if(k == 0){
                list.add(new ArrayList<Integer>(res));
            }
            for(int i = start; i <= n && k <= n - i + 1; i++){
                res.add(i);
                backtrack(list, res, i+1, n, k-1);
                res.remove(res.size() - 1);
            }
        }
    }
    

Log in to reply
 

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