leetcode之深搜递归回溯类-----1/167/653. two sum(记忆化搜索寻找和为给定值的两个数)

1.two sum

如[2,5,7,11],target = 9,寻找数组中两个和为target的两个数

可以直接递归深搜,但会导致TLE

导致TLE代码:

    void helper (const vector& nums, const int target, size_t idx, vector cur, vector &res) {
        if (idx <= nums.size()) {
            if (cur.size() == 2 && nums[cur[0]] + nums[cur[1]] == target) {
                res = cur;
                cur.pop_back();
            } else if (cur.size() > 2) {
                return;
            }
        }
        
        for (size_t i = idx; i < nums.size(); i++) {
            cur.push_back(i);
            helper(nums, target, i + 1, cur, res);
            cur.pop_back();
        }
    }


这种题尤其two sum需要直接找两个变量,用一个map记录每个数对应的索引,然后遍历每个数时寻找target-cur这个数在map里是否存在即可

题1代码:

vector twoSum(vector& nums, int target) {
        vector res;
        if (nums.empty()) {
            return res;
        }
        
        unordered_map hmap;
        for (int i = 0; i < nums.size(); i++) {
            if (hmap.find(target - nums[i]) != hmap.end()) {
                res.push_back(i);
                res.push_back(hmap[target - nums[i]]);
                break;
            }
            hmap[nums[i]] = i;
        }
        
        return res;
    }


2.two sum

数组改为有序数组,需要升序输出索引,并且索引从1开始而不是从0开始

思路和上一题完全一样,注意因为是有序,所以在找到结果时,先push已存在的索引,然后push当前索引i

题167代码:

    vector twoSum(vector& numbers, int target) {
        vector res;
        if (numbers.empty()) {
            return res;
        }
        
        unordered_map hmap;
        for (int i = 0; i < numbers.size(); i++) {
            if (hmap.find(target - numbers[i]) != hmap.end()) {
                res.push_back(hmap[target - numbers[i]]);
                res.push_back(i + 1);
                break;
            }
            hmap[numbers[i]] = i + 1;
        }
        
        return res;
    }


3. two sum - input is a BST

输入改成在二叉树,但解法毫无区别,遍历改为前序递归二叉树即可

    bool helper (TreeNode *cur, const int k, unordered_set &hset) {
        if (cur) {
            if (hset.find(k - cur->val) != hset.end()) {
                return true;
            }
            
            hset.insert(cur->val);
            if (helper(cur->left, k, hset)) {
                return true;
            }
            return helper(cur->right, k, hset);
        } else {
            return false;
        }
    }
    
    bool findTarget(TreeNode* root, int k) {
        if (!root) {
            return false;
        }
        
        unordered_set hset;
        return helper(root, k, hset);
    }


你可能感兴趣的:(two,sum,记忆化搜索)