46.Permutations
回溯法:
使用回溯法。
额外的空间开销是 map<int,int> use,用于记录哪些元素已经被使用了。
class Solution {
public:
vector<vector<int>> ans;
vector<int> temp;
map<int,int> use;
vector<vector<int>> permute(vector<int>& nums) {
dfs(0, nums);
return ans;
}
void dfs(int count, vector<int>& nums){
if(count == nums.size()){
ans.push_back(temp);
return;
}
for(int i=0; i < nums.size(); i++){
if(use[i] != 1){
temp.push_back(nums[i]);
use[i] = 1;
dfs(count+1, nums);
temp.pop_back();
use[i] = 0;
}
}
}
};
48.Rotate Image
建立辅助矩阵 + 直接旋转:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
vector<vector<int>> temp = matrix;
int len = matrix.size();
for(int i=0; i<len; i++){
vector<int> nums = temp[i];
for(int j=0; j<len; j++){
matrix[j][len-1-i] = nums[j];
}
}
}
};
49.Group Anagrams
建字母表统计字母个数 + 建哈希表匹配字母个数:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int len = strs.size();
int count = 0;
vector<map<char,int>> match;
vector<vector<string>> ans;
for(int i=0; i<len; i++){
map<char,int> temp;
for(int j=0; j<strs[i].length(); j++)
temp[ strs[i][j] ]++;
int pos = 0;
for(pos=0; pos<count; pos++){
if(match[pos] == temp){
ans[pos].push_back(strs[i]);
break;
}
}
if(pos == count){
match.push_back(temp);
vector<string> add;
add.push_back(strs[i]);
ans.push_back(add);
count++;
}
}
return ans;
}
};
将字符串排序 + 建哈希表存字符串和对应于答案的位置:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
int len = strs.size();
map<string,int> match;
vector<vector<string>> ans;
for(int i=0; i<len; i++){
string temp = strs[i];
sort(temp.begin(), temp.end());
if(match.count(temp))
ans[match[temp]].push_back(strs[i]);
else{
match[temp] = ans.size();
vector<string> add;
add.push_back(strs[i]);
ans.push_back(add);
}
}
return ans;
}
};
53.Maximum Subarray
动态规划:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
vector<int> dp;
int len = nums.size();
int ans = nums[0];
dp.push_back(nums[0]);
for(int i=1; i<len; i++){
dp.push_back(nums[i]);
if(dp[i-1] + nums[i] > dp[i])
dp[i] = dp[i-1] + nums[i];
ans = max(ans, dp[i]);
}
return ans;
}
};
55.Jump Game
贪心法:
从数组的尾部开始往前找,找到可以到达最后一个位置的,离第一个位置最近的位置。
最后判断这个位置是不是数组的第一个位置。
class Solution {
public:
bool canJump(vector<int>& nums) {
int len = nums.size();
int pos = len-1;
for(int i=len-1; i>=0; i--){
if(i+nums[i] >= pos)
pos = i;
}
return pos == 0;
}
};