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);
}
};