Stone Game with Recursion

Many days ago I showed how to use dynamic programming to solve the stones game question. see here

Dynamic programming is no doubt a very efficient way to solve this question. However, a recursive algorithm would be more intuitive and easy to understand, hence give better maintainability. With a little hack, e.g. caching, we can still reach a pretty good performance using recursion.

Problem reviewed

from lintcode
There is a stone game. At the beginning of the game, the player picks n piles of stones in a line.

The goal is to merge the stones in one pile observing the following rules:

At each step of the game, the player can merge two adjacent piles to a new pile.
The score is the number of stones in the new pile.
You are to determine the minimum of the total score.

Example
For [4, 1, 1, 4], in the best solution, the total score is 18:

  1. Merge second and third piles => [4, 2, 4], score +2
  2. Merge the first two piles => [6, 4],score +6
  3. Merge the last two piles => [10], score +10
    Other two examples:
    [1, 1, 1, 1] return 8
    [4, 4, 5, 9] return 43
/**
 * GIVEN:
 * A stone game:
 * - a list of stone numbers in a line
 * - you can merge two adjacent stone into a pile
 * - and you can merge two adjacent piles/stones into one bigger pile
 * - each time you merge one pile, you get a score
 *   - score = total score of left pile + total score of right pile
 *
 * ASK:
 * Mimnimum of the total score
 *
 * ANALYSIS:
 * Think from the last step:
 * There are so many different ways to merge the stones
 * But at the end you will have only two piles
 * And you will just merge the two piles into one
 * Getting the score = all stones add up together
 *
 * Thus:
 *   - the score you get in the last-time merge is known
 *
 * Now think a bit more:
 * Each pile was originally merged from two smaller piles
 * With a score = all stones of left pile and right pile added up together
 *
 * Deduce the formula:
 *
 * possibilities of final scores of a list of N stones =
 *  sum of all stones in the list
 *    +
 *  possibilities of the sum of the final scores of merging each of its two sublists,
 *  where one list has X stones and theother list has Y stones
 *
 *  and you can go on and on...
 *
 * so we can see this is a recursive function
 * that keeps processing a list of N stones
 * and inside the function you need a loop
 * to iterate the {(x, y) | x + y = N}
 *
 * and our target is to find the smallest in this greate searching space.
 *
 * With this in mind we know how to test the correctness now.
 * However, this search is not optimal in terms of performance.
 *
 * We just want the minimal, let's optimize:
 *  the minimal score of merging a list of N stones =
 *    sum of all stones in the list
 *      +
 *    minimal score of possibilities of the sum of the final scores
 *    of merging each of its two sublists, where one list has X stones
 *    and the other list has Y stones
 *
 */

public class Solution {
    /**
     * @param A: An integer array
     * @return: An integer
     */
    public int stoneGame(int[] A) {

        if (A == null || A.length <= 0) return 0;

        this.stones = A;
        this.cache = new int[A.length][A.length];

        int start = 0;
        int end = A.length - 1;
        return getScore(start, end);
    }

    private int[][] cache = null;

    private int getScore(int start, int end) {
        // cache logic
        if (this.cache[start][end] != 0) return this.cache[start][end];

        // real business logic
        if (start >= end) return 0;
        int rangeSum = sumRange(start, end);
        boolean isAdjacent = (start + 1) == end;
        int answer = 0;
        if (isAdjacent) {
            answer = rangeSum;
        } else {
            int minMergeScore = minScore(start, end);
            answer = rangeSum + minMergeScore;
        }

        // cache and return answer
        this.cache[start][end] = answer;
        return answer;
    }

    private int minScore(int start, int end) {
        int min = Integer.MAX_VALUE;
        for(int x = start; x < end; x++) {
            int score = getScore(start, x) + getScore(x + 1, end);
            min = Math.min(min, score);
        }
        return min;
    }

    private int[] stones = null;
    private int sumRange(int start, int end) {
        int sum = 0;
        for(int i = start; i <= end; i++) {
            sum += this.stones[i];
        }
        return sum;
    }

}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末捶障,一起剝皮案震驚了整個濱河市疏遏,隨后出現(xiàn)的幾起案子萝勤,更是在濱河造成了極大的恐慌,老刑警劉巖甫匹,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡块攒,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進店門金砍,熙熙樓的掌柜王于貴愁眉苦臉地迎上來局蚀,“玉大人,你說我怎么就攤上這事恕稠±派穑” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵鹅巍,是天一觀的道長千扶。 經(jīng)常有香客問我,道長骆捧,這世上最難降的妖魔是什么澎羞? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮敛苇,結果婚禮上妆绞,老公的妹妹穿的比我還像新娘。我一直安慰自己枫攀,他們只是感情好括饶,可當我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著来涨,像睡著了一般图焰。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上蹦掐,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天技羔,我揣著相機與錄音僵闯,去河邊找鬼。 笑死藤滥,一個胖子當著我的面吹牛鳖粟,可吹牛的內容都是我干的。 我是一名探鬼主播超陆,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼牺弹,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了时呀?” 一聲冷哼從身側響起张漂,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎谨娜,沒想到半個月后航攒,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡趴梢,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年漠畜,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片坞靶。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡憔狞,死狀恐怖,靈堂內的尸體忽然破棺而出彰阴,到底是詐尸還是另有隱情瘾敢,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布尿这,位于F島的核電站簇抵,受9級特大地震影響,放射性物質發(fā)生泄漏射众。R本人自食惡果不足惜碟摆,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望叨橱。 院中可真熱鬧典蜕,春花似錦、人聲如沸罗洗。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽栖博。三九已至,卻和暖如春厢洞,著一層夾襖步出監(jiān)牢的瞬間仇让,已是汗流浹背典奉。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留丧叽,地道東北人卫玖。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像踊淳,于是被迫代替她去往敵國和親假瞬。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,336評論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,511評論 0 23
  • 今日繪畫書寫感受:每一個人來到世間都有屬于自己的不同角色迂尝,我們要定位好才可以詮釋好不同的位置脱茉,這樣才不會迷失自己。
    范雨萱閱讀 176評論 0 0
  • 首先得承認垄开,有時候我也闖紅燈琴许。 我常常騎著電動車,穿梭在這個不大不小溉躲、而人口眾多的省會城市榜田,總是多多少少會罵幾次娘...
    莫明妙閱讀 328評論 0 1