Help !!! can not pass this code !! said time limited


  • 0
    M
    public class Solution {
    List<List<Integer>> result;
    List<Integer> list;
    public List<List<Integer>> combine(int n, int k) {
        result = new ArrayList<List<Integer>>();
        if(n < k)
            return result;
        list = new ArrayList<Integer>();
        helper(n, k);
        return result;
    }
    
    private void helper(int n, int k)    {
        if(k == 0)  {
            result.add(list);
            return;
        }
        
         int  len = list.size();
        for(int i = len + 1; i <= n; i++)  {
            list.add(i);
            helper(n, k - 1);
            list.remove(len);
        }
        
        return;
    }
    

    }


  • 0
    L

    Hi miceteat,

    You have some bugs. Below is solution based on yours.

    public class Solution {
    List<List<Integer>> result;
    List<Integer> list;
    public List<List<Integer>> combine(int n, int k) {
        result = new ArrayList<List<Integer>>();
        if(n < k)
            return result;
        list = new ArrayList<Integer>();
        helper(1, n, k);
        return result;
    }
    
    private void helper(int start, int end, int k)    {
        if(k == 0)  {
            List<Integer> l = new ArrayList<Integer>();
            l.addAll(list);
            result.add(l);
            return;
        }
    
        for(int i = start; i <= end; i++)  {
            list.add(i);
            helper(i + 1, end, k - 1);
            list.remove(list.size() - 1);
        }
    
        return;
    }
    }
    

    First bug:

        if(k == 0)  {
            List<Integer> l = new ArrayList<Integer>();
            l.addAll(list);
            result.add(l);
            return;
        }
    

    Second bug:

    list should remove the last element, not the len.

    list.remove(list.size() - 1);
    

    Third bug:

        // Not from len + 1, but from list.last_value + 1
        for(int i = len + 1; i <= n; i++)  {
            list.add(i);
            helper(n, k - 1);
            list.remove(len);
        }

Log in to reply
 

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