8.21刷题笔记

46.全排列

class Solution {
public:
	vector<vector<int>> permute(vector<int>& nums) {
		vector<vector<int>> res;
		traceback(res, nums, 0, nums.size());
		return res;
	}
	
	void traceback(vector<vector<int>>& res, vector<int>& nums, int first, int len) {
		if (first == len) {
			res.emplace_back(nums);
			return;
		}
		for (int i = first; i < len; i++) {
			swap(nums[first], nums[i]);
			traceback(res, nums, first + 1, len);
			swap(nums[first], nums[i]);
		}
	}
}

72.编辑距离

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size();
        int n = word2.size();
        if (m == 0 || n == 0) return m + n;
        vector<vector<int>>dp(m + 1, vector<int>(n + 1));
        for (int i = 1; i < m + 1; i++) {
            dp[i][0] = i;           
        }
        for (int j = 1; j < n + 1; j++) {
            dp[0][j] = j;
        }
        for (int i = 1; i < m + 1; i++) {
            for (int j = 1; j < n + 1; j++) {
                int left = dp[i - 1][j] + 1;
                int down = dp[i][j - 1] + 1;
                int left_down = dp[i - 1][j - 1];
                if (word1[i - 1] != word2[j - 1]) left_down += 1;
                dp[i][j] = min(left, min(down, left_down));
            }
        }
        return dp[m][n];
    }
};

15.三数之和

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int n = nums.size();
        sort(nums.begin(), nums.end());
        vector<vector<int>> ans;
        for (int first = 0; first < n; first++) {
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            int target = -nums[first];
            int third = n - 1;
            for (int second = first + 1; second < n; second++) {
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                while (nums[second] + nums[third] > target && third > second) {
                    third--;
                }
                if (second == third) {
                    break;
                }
                if (nums[second] + nums[third] == target) {
                    ans.push_back({nums[first], nums[second], nums[third]});
                }
            }
        }
        return ans;
    }
};

69.x的平方根

class Solution {
public:
    int mySqrt(int x) {
        if (x == 0) {
            return 0;
        }

        double x0 = x, C = x;
        while (true) {
            double x1 = x0 - (x0 * x0 - C) / (2 * x0);
            if (fabs(x0 - x1) < 1e-7) {
                break;
            }
            x0 = x1;
        }
        return int(x0);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值