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){
            if(k==0){
                res.add(new ArrayList<>(list));
                return;
            }
            
            for(int i=cur; i<=n-k+1; ++i){  
                list.add(i);
                dfs(i+1, n, k-1, list, res);
                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.