Simple DFS with little trick beats 90%

  • 0

    The trick here is to prune dfs:
    say we have n numbers left and need to pick up k, the range of start point is [1 ... n-k+1]

    public class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> res = new ArrayList<>();
            dfs(1, n, k, new ArrayList<>(), res);
            return res;
        public void dfs(int cur, int n, int k, List<Integer> list, List<List<Integer>> res){
                res.add(new ArrayList<>(list));
            for(int i=cur; i<=n-k+1; ++i){  
                dfs(i+1, n, k-1, list, res);

Log in to reply

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