Target Sum

題目

You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.

Find out how many ways to assign symbols to make sum of integers equal to target S.

Example 1:

Input: nums is [1, 1, 1, 1, 1], S is 3. 
Output: 5
Explanation: 

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

There are 5 ways to assign symbols to make the sum of nums be target 3.
Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.

答案

巨短的dfs答案

class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        return dfs(nums, 0, 0, S);
    }
    
    public int dfs(int[] nums, int index, int curr_sum, int S) {
        if(index == nums.length) return (curr_sum == S)?1:0;
        int ways = dfs(nums, index + 1, curr_sum + nums[index], S) + dfs(nums, index + 1, curr_sum - nums[index], S);
        return ways;
    }
}

下面用dp 優(yōu)化下時間
這道題要改成dp有點tricky
我本來的想法是在dfs遞歸計算的同時記錄 dp[當(dāng)前的sum][當(dāng)前的index]的值
但是這樣做有個問題刻像,就是curr_sum是有可能小于0的萍肆,這樣就會引發(fā)異常

所以我想偷懶用HashMap來替代dp數(shù)組,代碼如下

class Solution {
    class Pair {
        int curr_sum;
        int index;
        public Pair(int sum, int i) { curr_sum = sum; index = i;}
    }

    public int findTargetSumWays(int[] nums, int S) {
        Map<Pair, Integer> dfs_memory = new HashMap<Pair, Integer>();
        return dfs(nums, dfs_memory, 0, 0, S);
    }

    public int dfs(int[] nums, Map<Pair, Integer> dfs_memory, int index, int curr_sum, int S) {
        if(index == nums.length) {
            return (curr_sum == S)?1:0;
        }
        Pair key = new Pair(curr_sum, index);
        Integer memorized = dfs_memory.get(key);
        if(memorized == null) {
            int ways = dfs(nums, dfs_memory, index + 1, curr_sum + nums[index], S);
            ways += dfs(nums, dfs_memory, index + 1, curr_sum - nums[index], S);
            dfs_memory.put(key, ways);
            return ways;
        }
        return memorized;
    }
}

大概Hashmap有點慢,竟然超時了

最后調(diào)整了一下dp數(shù)組的細(xì)節(jié)就過了嗓违,代碼如下

class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        int[][] dfs_memory = new int[2001][nums.length];
        for(int i = 0; i < dfs_memory.length; i++) Arrays.fill(dfs_memory[i], -1);
        return dfs(nums, dfs_memory, 0, 0, S);
    }

    public int dfs(int[] nums, int[][] dfs_memory, int index, int curr_sum, int S) {
        if(index == nums.length) {
            return (curr_sum == S)?1:0;
        }
        int adjusted_currsum = curr_sum + 1000;
        if(dfs_memory[adjusted_currsum][index] == -1) {
            dfs_memory[adjusted_currsum][index] = dfs(nums, dfs_memory, index + 1, curr_sum + nums[index], S);
            dfs_memory[adjusted_currsum][index] += dfs(nums, dfs_memory, index + 1, curr_sum - nums[index], S);
        }
        return dfs_memory[adjusted_currsum][index];
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市社证,隨后出現(xiàn)的幾起案子警医,更是在濱河造成了極大的恐慌,老刑警劉巖典徘,帶你破解...
    沈念sama閱讀 212,029評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蟀苛,死亡現(xiàn)場離奇詭異,居然都是意外死亡逮诲,警方通過查閱死者的電腦和手機帜平,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,395評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來梅鹦,“玉大人裆甩,你說我怎么就攤上這事∑胨簦” “怎么了嗤栓?”我有些...
    開封第一講書人閱讀 157,570評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我茉帅,道長叨叙,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,535評論 1 284
  • 正文 為了忘掉前任堪澎,我火速辦了婚禮擂错,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘樱蛤。我一直安慰自己钮呀,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 65,650評論 6 386
  • 文/花漫 我一把揭開白布昨凡。 她就那樣靜靜地躺著爽醋,像睡著了一般。 火紅的嫁衣襯著肌膚如雪土匀。 梳的紋絲不亂的頭發(fā)上子房,一...
    開封第一講書人閱讀 49,850評論 1 290
  • 那天,我揣著相機與錄音就轧,去河邊找鬼证杭。 笑死,一個胖子當(dāng)著我的面吹牛妒御,可吹牛的內(nèi)容都是我干的解愤。 我是一名探鬼主播,決...
    沈念sama閱讀 39,006評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼乎莉,長吁一口氣:“原來是場噩夢啊……” “哼送讲!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起惋啃,我...
    開封第一講書人閱讀 37,747評論 0 268
  • 序言:老撾萬榮一對情侶失蹤哼鬓,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后边灭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體异希,經(jīng)...
    沈念sama閱讀 44,207評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,536評論 2 327
  • 正文 我和宋清朗相戀三年绒瘦,在試婚紗的時候發(fā)現(xiàn)自己被綠了称簿。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,683評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡惰帽,死狀恐怖憨降,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情该酗,我是刑警寧澤授药,帶...
    沈念sama閱讀 34,342評論 4 330
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響悔叽,放射性物質(zhì)發(fā)生泄漏航邢。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,964評論 3 315
  • 文/蒙蒙 一骄蝇、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧操骡,春花似錦九火、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,772評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至是掰,卻和暖如春虑鼎,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背键痛。 一陣腳步聲響...
    開封第一講書人閱讀 32,004評論 1 266
  • 我被黑心中介騙來泰國打工炫彩, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人絮短。 一個月前我還...
    沈念sama閱讀 46,401評論 2 360
  • 正文 我出身青樓江兢,卻偏偏與公主長得像,于是被迫代替她去往敵國和親丁频。 傳聞我的和親對象是個殘疾皇子杉允,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,566評論 2 349

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,738評論 0 33
  • 文/未名師姐 很多名人酷愛跑步改基,如美國前總統(tǒng)小布什、臺灣地區(qū)領(lǐng)導(dǎo)人馬英九署穗、著名作家村上春樹寥裂。 小布什是第一位跑過全...
    未名師姐閱讀 1,864評論 1 4
  • 倩兮_b90b閱讀 115評論 0 0
  • 去年十二月初,到北京國家會議中心參加一個展會案疲,因為行程比較寬松封恰,便在北京玩了兩天。一天下午褐啡,去了北京西城動物園诺舔,在...
    劍膽v琴心閱讀 611評論 2 1