0
votes

I was wondering why the code would throw an error: incompatible types: List cannot be converted to LinkedList.

However, it could run when I change the method helper to:

public void helper(String curr, List res,int left,int right,int n){

or I change the code that calls the constructor: LinkedList res = new LinkedList();

class Solution {
public List<String> generateParenthesis(int n) {
   List<String> res = new LinkedList<String>();
    helper("",res,0,0,n);
    return res;        
}

public void helper(String curr, LinkedList<String> res,int left,int 
right,int n){  
    if(right==n) {res.add(curr); return;}
    if(left<n) helper(curr+"(",res,left+1,right,n);
    if(right<left) helper(curr+")",res,left,right+1,n);
    }
}
1
You're sending an argument that's typed with the parameter's super-type. This is not allowed. The best to do here is change the method's parameter type to List<String> - ernest_k
A List<String> might not necessary be a LinkedList<String>, right? It could be an ArrayList<String> or some other kind of list. What don't you understand? - Sweeper
You have restricted the parameter type to only LinkedList, which means you cannot pass any other implementation of List or the super type itself. - deHaar
In my view, I have created "res" which has the type of "LinkedList". Why I couldn't pass it to the method "helper", which has a parameter "LinkedList". AM I right? Thanks - s666

1 Answers

2
votes
List<String> res = new LinkedList<>();

In this line you are assigning your LinkedList to a List type variable. So the type of your res variable will be List, not LinkedList.

And then you are trying to pass your List type variable to a method that takes LinkedList type of parameter. So this is not possible.

So you can either change the type of your res variable to LinkedList or change method parameter to a List