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
    }   
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末睦授,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡溉痢,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門蜜另,熙熙樓的掌柜王于貴愁眉苦臉地迎上來适室,“玉大人,你說我怎么就攤上這事举瑰〉妨荆” “怎么了?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵此迅,是天一觀的道長汽畴。 經常有香客問我旧巾,道長,這世上最難降的妖魔是什么忍些? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任鲁猩,我火速辦了婚禮,結果婚禮上罢坝,老公的妹妹穿的比我還像新娘廓握。我一直安慰自己,他們只是感情好嘁酿,可當我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布隙券。 她就那樣靜靜地躺著,像睡著了一般闹司。 火紅的嫁衣襯著肌膚如雪娱仔。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天游桩,我揣著相機與錄音牲迫,去河邊找鬼。 笑死借卧,一個胖子當著我的面吹牛盹憎,可吹牛的內容都是我干的。 我是一名探鬼主播谓娃,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼脚乡,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了滨达?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤俯艰,失蹤者是張志新(化名)和其女友劉穎捡遍,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體竹握,經...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡画株,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了啦辐。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片谓传。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖芹关,靈堂內的尸體忽然破棺而出续挟,到底是詐尸還是另有隱情,我是刑警寧澤侥衬,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布诗祸,位于F島的核電站跑芳,受9級特大地震影響,放射性物質發(fā)生泄漏直颅。R本人自食惡果不足惜博个,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望功偿。 院中可真熱鬧盆佣,春花似錦、人聲如沸械荷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽养葵。三九已至征堪,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間关拒,已是汗流浹背佃蚜。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留着绊,地道東北人谐算。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像归露,于是被迫代替她去往敵國和親洲脂。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,614評論 2 353

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗剧包。 張土汪:刷leetcod...
    土汪閱讀 12,743評論 0 33
  • LeetCode 刷題隨手記 - 第一部分 前 256 題(非會員)恐锦,僅算法題,的吐槽 https://leetc...
    蕾娜漢默閱讀 17,764評論 2 36
  • 1. LeetCode 56 : Merge Intervals Solution: First sort the...
    TQINJS閱讀 449評論 0 0
  • Scala的集合類可以從三個維度進行切分: 可變與不可變集合(Immutable and mutable coll...
    時待吾閱讀 5,815評論 0 4
  • 影院里噼里啪啦疆液,好不熱鬧一铅! 變形金剛不斷變換身形,男女主角跑來跑去堕油,好忙碌的樣子潘飘。 拯救地球!好偉大的使命掉缺!我卻一...
    GraceDong閱讀 169評論 0 2