backtracking and invariant during generating the parathese
righjt > left (open bracket and cloase barckst)
class Solution { //["((()))","(()())","(())()","()(())","()()()","())(()"] wrong case --> change right > left the numebr of bracket is the invariant List<String> res = new ArrayList<>(); public List<String> generateParenthesis(int n) { //back((new StringBuilder()).append('('),2*n, 1, n, n); back((new StringBuilder()), 2*n, 0, n, n); return res; } void back(StringBuilder temp, int n, int pos, int left, int right){//pos start from 1 if(pos >= n){ //temp.append(")"); // problem from here System.out.println(pos); res.add(temp.toString()); return; } if(left > 0 ){ temp.append("("); back(temp,n, pos+1, left-1, right); temp.setLength(temp.length()-1); } if(right > left ){ temp.append(")"); back(temp, n, pos+1, left, right-1); temp.setLength(temp.length()-1); } } }
Restore IP Addresses
//insert element into the string
class Solution { //invariant rule: each number are // use the immuniateble of String List<String> res = new ArrayList<String>(); public List<String> restoreIpAddresses(String s) { back(0, s, new String(), 0); return res; } void back(int next, String s, String str , int num){ //num: there are only three dots. if(num == 3){ //if(next==s.length()) return; if(!valid(s.substring(next, s.length()))) return; res.add(str+s.substring(next, s.length())); return; } //for each step, move one digit or two or three for(int i = 1; i <=3; i++ ){ //check string if(next+i > s.length()) continue; String sub = s.substring(next, next+i);// if(valid(sub)){ back(next+i, s, str+sub+'.', num+1); } } } boolean valid(String sub){ if(sub.length() == 0 || sub.length()>=4) return false; if(sub.charAt(0) == '0') { //System.out.println(sub.equals("0")); return sub.equals("0"); // not check '0' weired } int num = Integer.parseInt(sub); if(num >255 || num <0) return false; else return true; } }
//core idea: move one step or 2 step or three based on the question (0 - 255) also append . and substring
use string instead stringBuilder (immuatable)