Java 20 ms using HashSet and Backtracking


  • 0
    V
    List<List<Integer>> toRet;
    public List<List<Integer>> findSubsequences(int[] nums) 
    {
        toRet = new ArrayList<List<Integer>>();
        if(nums.length < 2)
            return toRet;        
        dfs(nums, -1, new ArrayList<Integer>());
        return toRet;
    }
    void dfs(int[] nums, int ind, List<Integer> list)
    {
        if(list.size() > 1)
            toRet.add(new ArrayList<Integer>(list));        
        if(ind == nums.length - 1)
            return;
        HashSet<Integer> hs = new HashSet<Integer>();
        for(int i = ind + 1; i < nums.length; i++)
        {
            if(ind > -1 && nums[i] < nums[ind])
                continue;
            if(hs.contains(nums[i]))
                continue;
            hs.add(nums[i]);
            if(i == nums.length) break;
            list.add(nums[i]);
            dfs(nums, i, list);
            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.