LetCode의 동적 기획(二)

1. Word Break
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given s =  "leetcode" , dict =  ["leet", "code"] .
Return true because  "leetcode"  can be segmented as  "leet code" .
[Analysis]
DP 문제possible[i]를 S 문자열에 [0, i]로 정의한 하위 문자열이segmented by dictionary에 있을 수 있는지 여부입니다.
그러면
possible[i] = true if S[0, i] dictionary
= true if possible [k] = = true 및 S[k+1, j]는 dictionary에서 0               = false      if    no such k exist.
 
[Code]
실현할 때 앞에dummy 노드를 추가하면 세 가지 상황을 하나의 표현식에 통일시킬 수 있다.시간 복잡도 O (n^2)
bool wordBreak(string s, unordered_set<string> &dict) {
    string s2 = '#'+s;
    int len = s2.size();
    vector<bool> possible(len,0);
    possible[0] = true;
    for(int i=1;i<len;i++){
        for(int k=0;k<i;k++){
            possible[i] = possible[k] && dict.find(s2.substr(k+1,i-k))!=dict.end();
            if(possible[i]) break;
        }
    }
    return possible[len-1];
}

2. Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
함수 P[i, j] = 문자열 구간 [i, j]이palindrome인지 정의합니다.먼저 예를 들어 S='abccb', S=a b c b index = 0 1 2 3 P[0, 0=1 2 3 4 P[0, 0=1/eachchchar is a palindrome P[0, 1] a b c c c c b index = 0 1 2 3 4 P[0, 4 P[0, 0 0 0 4 P[0, 2] = 1 1 1 1 P[0, 2] = 1 P[0, 2] = 1 P[0, 2] = 1 P[0, 2] = 1 P[0, 2] = 1 P[0, 2] = 1 2 = 1 1 1 1 P[0, 2] = 1 P & 4 4 4 4 4 4 P & 2] = 2 = 2 ===2 = S[3 P & 2 & 2 = 1 & 2 = P[1 P & 1 & 2 =[1 P & 1 & 1,2], P[2,3]=S[2]==S[3], P[3,3]=1........이로부터 법칙 P[i, j]=1 if i==j=S[i]==S[j]if j=i+1=S[i]=S[j] & & P[i+1][j-1]if j>i+1의 실현은 다음과 같다.
public String longestPalindrome(String s) {
        int len = s.length();
		boolean [][] pal = new boolean[len][len];
		for(int i=0;i<len;i++){
			for(int j=0;j<len;j++)
				pal[i][j] = false;
		}
		int start = 0;
		int end = 0;
		int mLen = 0;
		for(int i=0;i<len;i++){
			for(int j=0;j<i;j++){
				pal[j][i] = (s.charAt(i)==s.charAt(j) && ((i-j<2) || pal[j+1][i-1]));
				if(pal[j][i] && mLen<i-j+1){
					mLen = i-j+1;
					start = j;
					end = i;
				}
			}
			pal[i][i] = true;
		}
		return s.substring(start, end+1);
    }

모든 문자열을 옮겨다니며, 문자열을 중심으로 회문을 검색하고 기록합니다
c++
string longestPalindrome(string s) {
        int startIndex = 0;
    int len = 0;
    int sI, eI;
    for(int i=0; i< s.size()-1; i++){
        if(s[i] == s[i+1]){
            sI = i;
            eI = i+1;
            Search(s, sI, eI, len, startIndex);
        }
        sI = i;
        eI = i;
        Search(s, sI, eI, len, startIndex);
    }
    if(len ==0)
        len = s.size();
    return s.substr(startIndex,len);
    }
    void Search(string &s, int sI, int eI, int &len, int &startIndex){
    int step = 1;
    while((sI-step)>=0 && (eI+step)<s.size()){
        if(s[sI-step] != s[eI+step])
           { break;}
        step++;
    }
    int wid = eI-sI+2*step-1;
    if(wid>len){
        len = wid;
        startIndex = sI-step +1;
    }
}

3. Triangle
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is  11  (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
Analysis:
DP problem, Transaction function: a[n][i] = a[n][i]+min(a[n-1][i], a[n-1][i-1]). Note that in this problem, "adjacent"of a[i][j] means a[i-1][j] and a[i-1][j-1], if available(not out of bound), while a[i-1][j+1] is not "adjacent"element.
If we do this from up to down, it is complicated. While from down to up, we could use only one array to scan every row to get result
Java
public int minimumTotal(List<List<Integer>> triangle) {
        int n = triangle.size();
        if(n==0) return 0;
        int m = triangle.get(n-1).size();
        int [] result = new int[m];
        for(int i=n-1;i>=0;i--){
        	for(int j=0;j<triangle.get(i).size();j++){
        		if(i==n-1){
        			result[j] = triangle.get(i).get(j);
        			continue;
        		}
        		result[j] = Math.min(result[j], result[j+1])+triangle.get(i).get(j);
        	}
        }
        return result[0];
    }

c++
int minimumTotal(vector<vector<int> > &triangle) {
    int row = triangle.size();
    if(row == 0) return 0;
    vector<int> minV(triangle[row-1].size());
    for(int i = row-1; i>=0;i--){
        int col = triangle[i].size();
        for(int j=0; j<col;j++){
            if(i==row-1){
                minV[j] = triangle[i][j];
                continue;
            }
            minV[j] = min(minV[j],minV[j+1])+triangle[i][j];
        }
    }
    return minV[0];
    }

4.
미완성

좋은 웹페이지 즐겨찾기