Java 4ms Backtracking Solution with clean code, beats 93.89 %


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

Log in to reply
 

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