132. Palindrome Partitioning II
dp or memo recursion
1. dp formulation
2. ispalindrome based on the nature structure
class Solution { //optimal problem dp: how to divide into differern subsets //dp = min ();//how many cuts, dp[i][j] dp[i-1][j+1] //or mem recursive public int minCut(String s) { int n = s.length(); if(n==0) return 0; boolean[][] dp = new boolean[n+1][n+1];//0 to n-1 //preprocessing the string with dp[i][j] //check the [] //given fixed steps, check the palindrome* for(int step = 0; step < n;step++){ for(int i = 0; i+step<n; i++){ if(s.charAt(i)==s.charAt(i+step)){ if(step <=2 || dp[i+1][i+step-1]){ dp[i][i+step] = true; dp[i+step][i] = true; } } } } //cut[i][j] : minimal cut from i to j //initialize int[][] cut = new int[n+1][n+1]; for(int i = 0 ;i < n;i++){ for(int j = i; j<n; j++){ cut[i][j] = j-i; } } //cut[0][j] = min(cut[0][j], cut[0][i-1] +1(if dp[i][j]==true)) for(int j = 0; j<n; j++){ for(int i = 1; i<=j; i++){ if(dp[0][j]){ cut[0][j] = 0; }else if(dp[i][j]){ cut[0][j]= Math.min(cut[0][j], cut[0][i-1]+1); } } } return cut[0][n-1]; } }
79. Word Search
the key point is a||b||c||d; //I guess because of the || rule.....
class Solution { void initialize(boolean[][] visited){ for(int i = 0; i<visited.length; i++){ for(int j = 0; j<visited[0].length; j++){ visited[i][j] = false; } } } //version 2 without visited public boolean exist(char[][] board, String word) { if(word.length()==0) return false; System.out.println(word.charAt(0)=='C'); //if there exists one way return true , else return fasle boolean[][] visited = new boolean[board.length][board[0].length]; for(int i = 0; i<board.length; i++){ for(int j = 0; j<board[0].length; j++){ initialize(visited); if(back(board, visited, i,j, word,0)) return true; } } //System.out.println("test"); return false; } boolean back(char[][] board,boolean[][] visited, int i, int j ,String word, int pos){ //break codition if(i<0 || i >= board.length || j <0 || j>= board[0].length){ return false; } if(visited[i][j]) return false; if(word.charAt(pos) != board[i][j]) return false; if(word.charAt(pos) == board[i][j] && pos == word.length()-1) return true; visited[i][j] = true; //else return false; //board[i][j] = '#'; /*boolean up = back(board, visited, i-1, j,word, pos+1); boolean down = back(board, visited, i+1, j,word, pos+1); boolean left = back(board, visited, i, j-1,word, pos+1); boolean right = back(board, visited, i, j+1,word, pos+1);*/ boolean res = back(board, visited, i-1, j,word, pos+1) || back(board, visited, i+1, j,word, pos+1) || back(board, visited, i, j-1,word, pos+1)||back(board, visited, i, j+1,word, pos+1); visited[i][j] = false; //board[i][j] = word.charAt(pos); //return up||down||left||right; return res; } }