Algorithms ladder I

24 Dec

Mission:

  • lintcode 13 strStr
  • lintcode 17 Subsets
  • lintcode 18 SubsetsII
  • lintcode 15 Permutation
  • lintcode 16 Permutation II
  • lintcode 594 strStr II: A lintcode-only problem, requires O(m+n) solution for substring index, see cnblog. Also see java solution Or Princeton CS Robin-Karp.

Codes:

13 strStr (easy)

Note: use two layers of iteration, complexity O(mn)

package algorithm_ladder_I;

public class StrStr {
    
    public int strStr(String source, String target) {
        // corner case;
        if (source == null || target == null) {
            return -1;
        }
        int sl = source.length();
        int tl = target.length();
        if (sl < tl) {
            return -1;
        }
        
        // two layers of iteration.
        int i, j;
        for (i = 0; i <= sl-tl; i++) {
            for (j = 0; j < tl; j++) {
                char schar = source.charAt(i + j);
                char tchar = target.charAt(j);
                if (schar != tchar) break;
                // else continue;
            }
            if (j == tl) 
                return i;
        }
        return -1;
    }
    
    public static void main(String[] args) {    
        String source = "abcdabcdefg";
        String target = "bcd";
        
        StrStr ss = new StrStr();
        System.out.println(ss.strStr(source, target)); // expected to be 1
    }
}

17 Subsets (medium)

The key of ENUMERATION is to

  • Enumerate all possible values in current dimension
  • then traverse to next dimension

backtracking template:

// sorting the possible values!!

int Solution[MAXDIMENSION]
       backtrack(int dimension) { // backtrack the d^th dimension. (the d^th position)
            // prune
            if (solution[] will not be an answer) return;
            
            // check if solution is one of the solution
            if (dimension == MAX_DIMENSION) {
                check and record solution[];
                return;
            }
            
            /**
             * Enumerate all possible values in current dimension
             * then traverse to next dimension
             */
            for (x = possible values of current dimension) {
                solution[dimension] = x; // solution takes x at the dimension^th position.
                backtrack(dimension+1);
            }
    }
package algorithm_ladder_I;

import java.util.ArrayList;
import java.util.List;

/**
 * lintcode 17 medium
 * use dfs:
 */
public class Subsets {
    
    public List<List<Integer>> subsets(int[] nums) {
        
            List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        
        // CORNER CASE ------------- !!!
            if (nums == null || nums.length == 0) {
                return result;
            }
        
            backtrack(nums, 0, list, result);
            return result;
    }
    
    // d for dimension/position
    private void backtrack(int[] nums, int d, List<Integer> list, List<List<Integer>> res) {
            res.add(new ArrayList<Integer>(list));
            
            for (int pos = d; pos < nums.length; pos++) { // all possible values: ranging from nums[d] to nums[nums.length-1]
                list.add(nums[pos]);
                backtrack(nums, pos+1 ,list, res);
                list.remove(list.size()-1);
            }
    }

    
    public void printList(List<Integer> list) {
            System.out.print("[");
            for (int i : list) {
                System.out.print(i + " ");
            }
            System.out.print("] \n");
    }
    
    public static void main(String[] args) {
            int[] S = new int[] {1,2,3};
            Subsets ss = new Subsets();
            List<List<Integer>> result = ss.subsets(S);
            for (List<Integer> list : result) {
                ss.printList(list);
            }
    }   
}

Subsets II

Subsets II differs from subsetsI in that

  • there are duplicated elements in nums[]
  • to deal with duplicated elements: for every dimension, only list the FIRST duplicated at elements.
    • e.g. [1,2_1, 2_2] for dimension = 1, visit 2_1 then ignore 2_2 (when consider dimension = 3 you can still visit 2_2);
package algorithm_ladder_I;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * with duplication
 * When enumeration for possible values, only use duplicate elements once.
 */
public class SubsetsII {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        
        // CORNER CASE ------------- !!!
            if (nums == null || nums.length == 0) {
                return result;
            }
            
            Arrays.sort(nums);
            
            backtrack(nums, 0, list, result);
            return result;
    }
    
    
    private void backtrack(int[] nums, int d, List<Integer> list, List<List<Integer>> res) {
            res.add(new ArrayList<Integer>(list));
            
            for (int i = d; i < nums.length; i++) { // enumerate all possible values at dimension d
                if (i-1 >= d) { // the previous one in nums[] may also be enumerated
                    if (nums[i] == nums[i-1]) continue; // current nums[i] will not be repeatedly enumerated.
                }
                list.add(nums[i]);
                backtrack(nums, i+1, list, res);
                list.remove(list.size()-1);
            }
    }
    
    
    public void printList(List<Integer> list) {
        System.out.print("[");
        for (int i : list) {
            System.out.print(i + " ");
        }
        System.out.print("] \n");
  }

    public static void main(String[] args) {
        int[] S = new int[] {1,2,2};
        SubsetsII ss = new SubsetsII();
        List<List<Integer>> result = ss.subsetsWithDup(S);
        for (List<Integer> list : result) {
            ss.printList(list);
        }
  } 
}

Permutation

package algorithm_ladder_I;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Permutations {
    public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        
        // CORNER CASE ------------- !!!
        if (nums == null) {
            return result;
        }
        
        Arrays.sort(nums);
        
        backtrack(nums, 0, list, result);
        return result;
    }
    
    // @Param d dimension
    private void backtrack(int[] nums, int d, List<Integer> list, List<List<Integer>> res) {
            if (list.size() == nums.length) {
                res.add(new ArrayList<Integer>(list));
                return;
            }
            
            for (int i =  0; i < nums.length; i++) {
                if (list.contains(nums[i])) continue;
                list.add(nums[i]);
                backtrack(nums, i+1, list, res);
                list.remove(list.size()-1);
            }
    }
    
    public void printList(List<Integer> list) {
        System.out.print("[");
        for (int i : list) {
            System.out.print(i + " ");
        }
        System.out.print("] \n");
    }

    public static void main(String[] args) {
        int[] S = new int[] {1,2,3};
        Permutations ss = new Permutations();
        List<List<Integer>> result = ss.permute(S);
        for (List<Integer> list : result) {
            ss.printList(list);
        }
    }
}

16 Permutation II

The key is to maintain a PossibleElement Map. e.g. for nums = [1,2,2,3]
map = {1:1, 2:2, 3:1}
In backtracking, update map when list.add(elem). i.e.

              list.add(elem); possibleElem.put(elem, possibleElem.get(elem) - 1);
               backtrack(nums, list, res);
               list.remove(list.size()-1); possibleElem.put(elem, possibleElem.get(elem) + 1);
package algorithm_ladder_I;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PermutationsII {
    
    private Map<Integer, Integer> possibleElem;
    public List<List<Integer>> permuteUnique(int[] nums) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        
        // CORNER CASE ------------- !!!
        if (nums == null) {
            return result;
        }
        
        Arrays.sort(nums);
        possibleElem = new HashMap<>();
        for (int i : nums) {
            possibleElem.put(i, possibleElem.getOrDefault(i, 0) + 1); 
        }
        
        backtrack(nums, list, result);
        return result;
    }
    
    // @Param d dimension
    private void backtrack(int[] nums, List<Integer> list, List<List<Integer>> res) {
            if (list.size() == nums.length) {
                res.add(new ArrayList<Integer>(list));
                return;
            }
            
            for (int elem : possibleElem.keySet()) {
                if (possibleElem.get(elem) <= 0) continue;
                list.add(elem); possibleElem.put(elem, possibleElem.get(elem) - 1);
                backtrack(nums, list, res);
                list.remove(list.size()-1); possibleElem.put(elem, possibleElem.get(elem) + 1);
            }
    }
    
    public void printList(List<Integer> list) {
        System.out.print("[");
        for (int i : list) {
            System.out.print(i + " ");
        }
        System.out.print("] \n");
    }
    
    public static void main(String[] args) {
        int[] S = new int[] {1,2,2};
        PermutationsII ss = new PermutationsII();
        List<List<Integer>> result = ss.permuteUnique(S);
        for (List<Integer> list : result) {
            ss.printList(list);
        }
    }
}

594 strStr II

Robin-Karp Algorithm -- O(m+n) complexity
Two important properties of modulation

  1. (A+B) % Q = (A % Q + B % Q) % Q
  2. (A * B) % Q = ((A % Q)*B) % Q
    Robin-Karp algorithm can be derived solely based on this two equations.
package algorithm_ladder_I;

/**
 * The same as LintCode 13 but requires O(m+n) Solution
 * One possible solution is Robin-Karp Algorithm
 * 1) Use HashCode use modulation: HashCode(ABCD) = (A*31^3 + B*31^2 + C*31^1 + D*31^0) % BASE (note base as Q)
 *    property of module: (A+B) % Q =  (A % Q + B % Q) % Q
 *    property of module: (A * B) % Q = ((A % Q)*B) % Q
 *      therefore,
 *      to obtain (A*31^3 + B*31^2 + C*31^1 + D*31^0) % Q  :
 *          1. cal temp = (0*31 + A) % Q 
 *          2. cal temp = (temp*31 + B) % Q
 *          3. cal temp = (temp*31 + C) % Q
 *          4. cal temp = (temp*31 + D) % Q
 * 2) If known (A*31^3 + B*31^2 + C*31^1 + D*31^0) % Q 
 *    how to obtain (B*31^3 + C*31^2 + D*31^1 + E*31^0) % Q
 *      let x = A*31^3 + B*31^2 + C*31^1 + D*31^0
 *      let x' = B*31^3 + C*31^2 + D*31^1 + E*31^0
 *      x' = x*31 + E - A*31^4
 *      x' % Q = [(x - A*31^3) * 31 + E] % Q
 *             = [x % Q + A * (Q - 31^3 % Q) + E] % Q
 *     if (31^3 % Q) = RM is calculated beforehand then
 *      x' % Q = [x % Q + A * (Q - RM) + E] % Q
 *      
 */
public class StrStrII {
    
    
    public int strStr(String haystack, String needle) {
        // corner case:
        if (haystack == null || needle == null) {
            return -1;
        }
        if (needle.length() == 0) {
            return 0;
        }
        
        int Q = 100000;
        int M = needle.length();
        int N = haystack.length();
        
        if (M > N) {
            return -1;
        }
        
        // compute RM
        int RM = 1;
        for (int i = 1; i <= M-1; i++) {
            RM = (RM * 31) % Q;
        }
        
        int hashPattern = getHashCode(needle, Q);
        System.out.println("hashPattern: " + hashPattern);

        
        int hashCompare = getHashCode(haystack.substring(0, M), Q);
        for (int i = 0; i <= N-M; i++) {
            if (i != 0) { // update hashcode
                int originalInit = Character.getNumericValue(haystack.charAt(i-1)); 
                int newEnd = Character.getNumericValue(haystack.charAt(i+M-1));
                hashCompare = (31 * (hashCompare + originalInit * (Q - RM % Q)) + newEnd) % Q;
            }   
            System.out.println("hashCompare: " + hashCompare);
            if (hashCompare == hashPattern) {
                return i;
            } // else continue;
        }
        
        return -1;
    }
    
    private int getHashCode(String s, int Q) {
        char[] chars = s.toCharArray();
        int r = 0; 
        for (char c : chars) {
            r = (r*31 + Character.getNumericValue(c)) % Q;
        }
        return r;
    }
    
    public static void main(String[] args) {
        String haystack = "abcd";
        String needle = "bcd";
        StrStrII ss = new StrStrII();
        System.out.println(ss.strStr(haystack, needle)); // should be 1
    }   
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,542评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,596评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,021评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,682评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,792评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,985评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,107评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,845评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,299评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,612评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,747评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,441评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,072评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,828评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,069评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,545评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,658评论 2 350

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,740评论 0 33
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 17,738评论 2 36
  • 1. LeetCode 56 : Merge Intervals Solution: First sort the...
    TQINJS阅读 445评论 0 0
  • Scala的集合类可以从三个维度进行切分: 可变与不可变集合(Immutable and mutable coll...
    时待吾阅读 5,807评论 0 4
  • 影院里噼里啪啦,好不热闹! 变形金刚不断变换身形,男女主角跑来跑去,好忙碌的样子。 拯救地球!好伟大的使命!我却一...
    GraceDong阅读 166评论 0 2