leetcode-9

Subsets

Bit manipulation and map can be useful aside from backtracking

vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> results(pow(2,nums.size()), vector<int>());
        for(int i=1;i<=pow(2,nums.size());i++){
            for(int j=0;j<nums.size();j++){
                if((((i<<(nums.size()-1-j))&(1<<nums.size()-1))>>(nums.size()-1))==1){
                    results[i-1].push_back(nums[j]);
                }
            }
        }
        return results;
    }

Path Sum

Don't suppose that all elements are positive.
Pay attention to problem saying "root to leaf"

Path Sum III

class Solution {
public:
    int help(TreeNode* root, int sum, unordered_map<int, int>& store, int pre) {
        if (!root) return 0;
        root->val += pre;
        int res = (root->val == sum) + (store.count(root->val - sum) ? store[root->val - sum] : 0);
        store[root->val]++;
        res += help(root->left, sum, store, root->val) + help(root->right, sum, store, root->val);
        store[root->val]--;
        return res;
    }

    int pathSum(TreeNode* root, int sum) {
        unordered_map<int, int> store;
        return help(root, sum, store, 0);
    }
};

Up-to-bottom is faster and smaller than Bottom-to-Up as no need to store whole sums only need to store current value needed.
Use hashmap to store value makes searching occurrence faster.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,430評(píng)論 0 10
  • Determine whether an integer is a palindrome. An integer ...
    飛鳥與魚閱讀 224評(píng)論 0 0
  • 9 Palindrome Number 回文數(shù) Description:Determine whether an ...
    air_melt閱讀 155評(píng)論 1 1
  • 白日何短短,百年苦易滿。蒼穹浩茫茫,萬劫太極長(zhǎng)。麻姑垂兩鬢,一半已成霜。天公見玉女,大笑億千場(chǎng)。吾欲攬六龍,回車掛...
    果果開心閱讀 1,059評(píng)論 0 4
  • 走村日當(dāng)午,汗滴長(zhǎng)路土。 扶貧多艱難,日日奔波苦。 入戶訪貧寒,極目心內(nèi)堵。 蒸煎天地間,生民何得贖。
    依依原上草閱讀 234評(píng)論 0 2