My question is:
ArrayList<String> temp = new ArrayList<String>(r);
Without this line, I am inserting nothing into res
why?
Why without copying r
into a new temp ArrayList
, I am copying nothing to res
?
public class Solution {
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
ArrayList<String> r = new ArrayList<String>();
find(s, 0, r, res);
return res;
}
private void find(String s, int st, ArrayList<String> r, ArrayList<ArrayList<String>> res) {
if (st >= s.length()){
// This seems important. Without the next line, I am inserting
// nothing into "res". Why?
ArrayList<String> temp = new ArrayList<String>(r);
res.add(temp);
return;
} else {
for (int i=st; i<s.length();i++) {
if (isValid(s, st, i)) {
r.add(s.substring(st,i+1));
find(s, i + 1, r, res);
r.remove(r.size()-1);
}
}
}
}
private boolean isValid(String s, int st, int end) {
while (st < end) {
if (s.charAt(st) != s.charAt(end)) {
return false;
}
st++;
end--;
}
return true;
}
}