#include
#include
#include
#include
using namespace std;
class Solution {
public:
vector twoSum(vector& nums, int target) {
unordered_map m;
for (int i = 0; i < nums.size(); i++) {
if (m.count(target - nums[i])) {
return { i, m[target - nums[i]] };
}
m[nums[i]] = i;
}
return {};
}
};
int main() {
vector nums = { 2, 7, 11, 15 };
int target = 9;
vector res = Solution().twoSum(nums, target);
cout << "nums1_index = " << res[0] << endl;
cout << "nums2_index = " << res[1] << endl;
system("pause");
return 0;
}
#include
#include
#include
using namespace std;
typedef pair PII;
class Solution {
public:
vector twoSum(vector& nums, int target) {
int n = nums.size();
unordered_map m;
vector res;
for(int i = 0; i < n; i++){
if(m.count(target-nums[i])) {
res.push_back({i, m[target-nums[i]]});
}
m[nums[i]] = i;
}
return res;
}
};
int main() {
int target = 9;
vector nums = {2, 7, 5, 4, 1, 8, 12, 47};
vector res = Solution().twoSum(nums, target);
for(int i = 0; i < res.size(); i++)
cout << res[i].first <<" "<< res[i].second << endl;
return 0;
}
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *dummy = new ListNode(-1), *cur = dummy;
int carry = 0;
while(l1||l2){
int val1 = l1 ? l1->val:0;
int val2 = l2 ? l2->val:0;
int sum = val1 + val2 + carry;
carry = sum /10;
cur->next = new ListNode(sum%10);
cur = cur->next;
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
if(carry) cur->next = new ListNode(1);
return dummy->next;
}
};
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = 0, left = -1;
int n = s.size();
unordered_map m(n);
for(int i = 0; i < n; i++){
if(m.count(s[i])&&m[s[i]] > left){
left = m[s[i]];
}
m[s[i]] = i;
res = max(res, i-left);
}
return res;
}
};
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(!s.size()) return 0;
int n = s.size();
vector dp(n);
int j = 0;
bool flag = false;
int temp = 0;
int res = 1;
for(int i = 1; i < n; i++){
flag = false;
j = temp;
for(j; j < i; j++){
if(s[i] == s[j]){
dp[i] = 1;
temp = j+1;
flag = true;
}
}
if(!flag){
dp[i] = i - temp + 1;
}
res = max(res, dp[i]);
}
return res;
}
};
class Solution {
public:
double findMedianSortedArrays(vector& nums1, vector& nums2) {
int m = nums1.size(), n = nums2.size(), left = (m+n+1) / 2, right = (m+n+2) / 2;
return(findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0;
}
int findKth(vector& nums1, int i, vector& nums2, int j, int k){
if(i >= nums1.size()) return nums2[j+k-1];
if(j >= nums2.size()) return nums1[i+k-1];
if(k == 1) return min(nums1[i], nums2[j]);
int midval1 = (i + k/2 -1 < nums1.size()) ? nums1[i + k / 2 -1] : INT_MAX;
int midval2 = (j + k/2 -1 < nums2.size()) ? nums2[j + k / 2 -1] : INT_MAX;
if(midval1 < midval2){
return findKth(nums1, i + k / 2, nums2, j, k - k / 2);
} else {
return findKth(nums1, i, nums2, j + k / 2, k - k / 2);
}
}
};
class Solution {
public:
string longestPalindrome(string s) {
if(s.size()<2) return s;
int n = s.size(), maxLen = 0, start = 0;
for(int i = 0; i < n-1; i++){
searchP(s, i, i, start, maxLen);
searchP(s, i, i+1, start, maxLen);
}
return s.substr(start, maxLen);
}
void searchP(string s, int left, int right, int& start, int& maxLen){
while(left>=0&&right
class Solution {
public:
string longestPalindrome(string s) {
if(s.empty()) return "";
int n = s.size(), dp[n][n] = {0}, left = 0, len = 1;
for(int i = 0; i < n; i++){
dp[i][i] = 1;
for(int j = 0; j < i; j++){
dp[j][i] = (s[j] == s[i] && (i-j<2||dp[j+1][i-1]));
if(dp[j][i]&&len
class Solution {
public:
string longestPalindrome(string s) {
int n = s.size();
if(n<2) return s;
string res = "";
vector<int> f(n+1, 1);
for(int i = 0; i < n-1; i++){
int odd = 1, even = 1;
for(int j = i; j >= 0; j--){
if(odd == 1 && s[j] != s[2*i-j]) odd = 0;
if(even ==1 && s[j] != s[2*i-j+1]) even = 0;
if(even == 1) {
f[i] = 2*(i-j)+2;
if(f[i] > res.size()){
res = s.substr(j, f[i]);
}
}
if(odd == 1){
f[i] = 2*(i-j)+1;
if(f[i] > res.size()){
res = s.substr(j, f[i]);
}
}
if(odd==1||even==1) continue;
break;
}
}
return res;
}
};
#include
#include
#include
using namespace std;
class Solution {
public:
string maxP(string s) {
if (s.size() < 2) return s;
int n = s.size(), start = 0, maxLen = 0;
for (int i = 0; i < n - 1; i++) {
searchP(s, i, i, start, maxLen);
searchP(s, i, i + 1, start, maxLen);
}
return s.substr(start, maxLen);
}
void searchP(string s, int left, int right, int& start, int& maxLen) {
while (left >= 0 && right < s.size()&&s[left] == s[right]) {
--left, ++right;
}
if (maxLen < right - left - 1) {
start = left + 1;
maxLen = right - left - 1;
}
}
};
int main() {
string s = "aba";
string res = Solution().maxP(s);
cout << res << endl;
system("pause");
return 0;
}
class Solution {
public:
string convert(string s, int numRows) {
if(numRows <= 1) return s;
string res;
int size = 2*numRows-2, n = s.size();
for(int i = 0; i < numRows; i++){
for(int j = i; j < n; j += size){
res +=s[j];
int pos = j + size -2*i;
if(i != 0 && i != numRows - 1 && pos < n) res += s[pos];
}
}
return res;
}
};
#include
using namespace std;
class Solution {
public:
int reverse(int x) {
int res = 0;
while (x) {
if (abs(res) > INT_MAX) return 0;
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
};
int main() {
int x = 1463847412; //214748364
int result = Solution().reverse(x);
cout << result;
system("pause");
return 0;
}
class Solution {
public:
int myAtoi(string str) {
if(str.empty()) return 0;
int n = str.size();
long long res = 0;
int k = 0;
bool isminus = false;
while(k < n && str[k]==' ') k++;
if(str[k] == '+') k++;
else if(str[k] == '-') isminus = true, k++;
while(str[k] >= '0' && str[k] <= '9'){
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && str[k] - '0' > 7)) {
return (isminus == false) ? INT_MAX : INT_MIN;
}
res = res*10 + str[k]-'0', k++;
}
if(isminus) res *= -1;
return res;
}
};
class Solution {
public:
int myAtoi(string str) {
if (str.empty()) return 0;
int sign = 1, base = 0, i = 0, n = str.size();
while (i < n && str[i] == ' ') ++i;
if (i < n && (str[i] == '+' || str[i] == '-')) {
sign = (str[i++] == '+') ? 1 : -1;
}
while (i < n && str[i] >= '0' && str[i] <= '9') {
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
return (sign == 1) ? INT_MAX : INT_MIN;
}
base = 10 * base + (str[i++] - '0');
}
return base * sign;
}
};
class Solution {
public:
bool isPalindrome(int x) {
if(x<0) return false;
int div = 1;
while(x/div >= 10) div *= 10;
while(x > 0){
int left = x / div;
int right = x % 10;
if(left != right) return false;
x = ( x % div ) / 10;
div /= 100;
}
return true;
}
};
class Solution {
public:
int maxArea(vector& height) {
int res = 0, i = 0, j = height.size()-1;
while(i < j) {
res = max(res, min(height[i], height[j])*(j-i));
height[i] < height[j] ? i++: j--;
}
return res;
}
};
#include
#include
#include
using namespace std;
class Solution {
public:
vector letterCombinations(string digits) {
if (digits.empty()) return {};
vector res;
vector dict{ " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
letterCombinationsDFS(digits, dict, 0, "", res);
return res;
}
void letterCombinationsDFS(string& digits, vector& dict, int level, string out, vector& res) {
if (level == digits.size()) { res.push_back(out); return; }
string str = dict[digits[level] - '0'];//找到数字字符对应的字母
for (int i = 0; i < str.size(); ++i) {
letterCombinationsDFS(digits, dict, level + 1, out + str[i], res);
}
}
};
int main() {
vector res = Solution().letterCombinations("234");
for (int i = 0; i < res.size(); i++)
cout << res[i] << endl;
system("pause");
return 0;
}
#include
#include
#include
#include
using namespace std;
class Solution {
private:
vector res;
const string letterMap[10] = {
" ",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
void findCombinations(const string& digits, int index, const string& s) {
if (index == digits.size()) {
res.push_back(s);
return;
}
char c = digits[index];
assert( c >= '0' && c <= '9' && c != '1');
string letters = letterMap[c - '0'];
for (int i = 0; i < letters.size(); ++i) {
findCombinations(digits,index+1,s+letters[i]);
}
}
public:
vector letterCombinations(string digits) {
res.clear();
if (digits == "") return res;
findCombinations(digits,0,"");
return res;
}
};
int main() {
string digits = "23";
vector res = Solution().letterCombinations(digits);
for (int i = 0; i < res.size(); ++i) {
cout << res[i] << endl;
}
system("pause");
return 0;
}
class Solution {
public:
vector letterCombinations(string digits) {
vector chars = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if(digits.empty()) return vector();
vectorstate(1, "");
for(auto u : digits){
vector now;
for(auto c : chars[u-'2'])
for(auto s : state)
now.push_back(s+c);
state = now;
}
return state;
}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head->next) return NULL;
auto pre = head, cur = head;
for(int i = 0; i < n; i++) cur = cur->next;
if(!cur) return head->next;
while(cur->next){
cur=cur->next;
pre=pre->next;
}
pre->next = pre->next->next;
return head;
}
};
#include
#include
#include
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack parentheses;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]);
else {
if (parentheses.empty()) return false;
if (s[i] == ')' && parentheses.top() != '(') return false;
if (s[i] == ']' && parentheses.top() != '[') return false;
if (s[i] == '}' && parentheses.top() != '{') return false;
parentheses.pop();
}
}
return parentheses.empty();
}
};
int main() {
string s = "()[]{}";
bool res = Solution().isValid(s);
if (res == true)
cout << "true" << endl;
else
cout << "false" << endl;
system("pause");
return 0;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode *tail = &dummy;
while(l1&&l2){
if(l1->valval){
tail->next = l1;
l1 = l1->next;
}
else{
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
if(l1) tail->next = l1;
if(l2) tail->next = l2;
return dummy.next;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *dummy = new ListNode(-1), *cur = dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 ? l1 : l2;
return dummy->next;
}
};
class Solution {
public:
vector generateParenthesis(int n) {
vector res;
generateParenthesisDFS(n, n, "", res);
return res;
}
void generateParenthesisDFS(int left, int right, string out, vector&res){
if(left>right) return;
if(left==0&&right==0) res.push_back(out);
else{
if(left>0) generateParenthesisDFS(left-1,right,out+'(', res);
if(right) generateParenthesisDFS(left, right-1, out+')', res);
}
}
};
class Solution {
public:
int removeElement(vector& nums, int val) {
int j = 0;
for( int i = 0 ; i < nums.size() ; i ++ )
if( nums[i] != val )
nums[j++] = nums[i];
return j;
}
};
class Solution {
public:
vector searchRange(vector& nums, int target) {
if(nums.empty()) return {-1,-1};
int l = 0, r = nums.size()-1;
while(l>1;
if(target <= nums[mid]) r = mid;
else l = mid+1;
}
int res = l;
if(nums[res] != target) return{-1, -1};
l = 0, r = nums.size()-1;
while(l < r){
int mid = l+r+1>>1;
if(target >= nums[mid]) l= mid;
else r = mid -1;
}
return {res, l};
}
};
#include
#include
using namespace std;
class Solution {
public:
int searchInsert(vector& nums, int target) {
if (nums.empty()) return 0;
int l = 0, r = nums.size() - 1;
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
l = mid + 1;
else r = mid;
}
return r;
}
};
int main() {
vector nums = {1,3,5,6};
int target = 2;
int res = Solution().searchInsert(nums, target);
cout << res << endl;
system("pause");
return 0;
}
class Solution {
public:
string countAndSay(int n) {
if (n <= 0) return "";
string res = "1";
while (--n) {
string cur = "";
for (int i = 0; i < res.size(); ++i) {
int cnt = 1;
while (i + 1 < res.size() && res[i] == res[i + 1]) {
++cnt;
++i;
}
cur += to_string(cnt) + res[i];
}
res = cur;
}
return res;
}
};
#include
#include
#include
using namespace std;
class Solution {
public:
vector> combinationSum(vector& candidates, int target) {
vector> res;
vector out;
combinationSumDFS(candidates, target, 0, out, res);
return res;
}
void combinationSumDFS(vector& candidates, int target, int start, vector& out, vector>& res) {
if (target < 0) return;
if (target == 0) { res.push_back(out); return; }
for (int i = start; i < candidates.size(); ++i) {
out.push_back(candidates[i]);
combinationSumDFS(candidates, target - candidates[i], i, out, res);
out.pop_back();
}
}
};
int main() {
vector candidates = {2,3,6,7};
int target = 7;
vector> result = Solution().combinationSum(candidates, target);
for (int i = 0; i < result.size(); i++) {
for (int j = 0; j < result[i].size(); j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
system("pause");
return 0;
}
class Solution {
public:
int trap(vector& height) {
int res = 0, mx = 0, n = height.size();
vector dp(n, 0);
for(int i = 0; i < n; i++){
dp[i] = mx;
mx = max(mx, height[i]);
}
mx = 0;
for(int i = n - 1; i >= 0; i--){
dp[i] = min(dp[i], mx);
mx = max(mx, height[i]);
if(dp[i] > height[i]) res += dp[i] - height[i];
}
return res;
}
};
class Solution {
public:
string multiply(string num1, string num2) {
string res = "";
int m = num1.size(), n = num2.size();
vector vals(m+n);
for(int i = m-1; i >= 0; i--){
for(int j = n-1; j >= 0; j--){
int p1 = i + j, p2 = i + j + 1;
int sum = (num1[i]-'0')*(num2[j]-'0')+vals[p2];
vals[p1] += sum/10;
vals[p2] = sum % 10;
}
}
for(int val : vals){
if(!res.empty() || val != 0) res.push_back(val+'0');
}
return res.empty() ? "0" : res;
}
};
class Solution {
public:
bool isMatch(string s, string p) {
int i = 0, j = 0, iStar = -1, jStar = -1;
while(i < s.size()){
if(s[i] == p[j]||p[j] == '?'){
i++; j++;
}else if(p[j] == '*'){
iStar = i;
jStar = j++;
}
else if(iStar>=0){
i = ++iStar;
j = jStar+1;
}else return false;
}
while(j < p.size()&&p[j] == '*') ++j;
return j == p.size();
}
};
class Solution {
public:
int jump(vector& nums) {
int res = 0, n = nums.size(), i = 0, cur = 0;
while(cur < n-1){
++res;
int pre = cur;
for(; i <= pre; i++){
cur = max(cur, i+nums[i]);
}
}
return res;
}
};
#include
#include
using namespace std;
class Solution {
public:
vector> permute(vector& num) {
vector> res;
permuteDFS(num, 0, res);
return res;
}
void permuteDFS(vector& num, int start, vector>& res) {
if (start >= num.size()) res.push_back(num);
for (int i = start; i < num.size(); ++i) {
swap(num[start], num[i]);
permuteDFS(num, start + 1, res);
swap(num[start], num[i]);
}
}
};
int main() {
vector num{1,2,3};
vector> res = Solution().permute(num);
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[i].size(); j++)
cout << res[i][j];
cout << endl;
}
system("pause");
return 0;
}
#include
#include
#include
using namespace std;
class Solution {
private:
vector> res;
vector used;
void generatePermutation(const vector& nums, int index, vector& p) {
if (index == nums.size()) {
res.push_back(p);
return;
}
for (int i = 0; i < nums.size(); i++) {
if (!used[i]) {
p.push_back(nums[i]);
used[i] = true;
generatePermutation(nums, index + 1, p);
p.pop_back();
used[i] = false;
}
}
return;
}
public:
vector> permute(vector& nums) {
res.clear();
if (nums.size() == 0)
return res;
used = vector(nums.size(), false);
vector p;
generatePermutation(nums, 0, p);
return res;
}
};
int main() {
vector num{1, 2, 3};
vector> res = Solution().permute(num);
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[i].size(); j++)
cout << res[i][j];
cout << endl;
}
system("pause");
return 0;
}
#include
#include
using namespace std;
vector path;
vector st;
void dfs(int n, int u) {
if (u == n+1) {
for (auto x : path) cout << x << " ";
cout << endl;
}
for (int i = 1; i <= n; i++) {
if (!st[i]) {
st[i] = true;
path.push_back(i);
dfs(n, u + 1);
path.pop_back();
st[i] = false;
}
}
}
int main() {
int n;
cin >> n;
st = vector(n, false);
dfs(n, 1);
system("pause");
return 0;
}
class Solution {
public:
void rotate(vector>& matrix) {
int n = matrix.size();
for(int i = 0; i < n; i++){
for(int j = 0; j < i; j++){
swap(matrix[i][j], matrix[j][i]);
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n/2 ; j++){
swap(matrix[i][j], matrix[i][n-1-j]);
}
}
}
};
class Solution {
public:
vector> groupAnagrams(vector& strs) {
vector> res;
unordered_map> m;
for(string str:strs){
string t = str;
sort(t.begin(), t.end());
m[t].push_back(str);
}
for(auto a:m){
res.push_back(a.second);
}
return res;
}
};
class Solution {
public:
double myPow(double x, int n) {
if(n<0) return 1/pow(x, n);
else return pow(x, n);
}
double pow (double x, int n){
if(n == 0) return 1;
double y = pow(x, n/2);
if(n % 2 == 0) return y*y;
else return y*y*x;
}
};
class Solution {
public:
static const int N = 1010;
bool col[N], dg[N], udg[N];
vector> solveNQueens(int n) {
vector> res;
vector queens(n,string(n, '.'));
dfs(0, queens, res);
return res;
}
void dfs(int u, vector& queens, vector>& res){
int n = queens.size();
if(u == n){
res.push_back(queens);
return;
}
for(int i = 0; i < n; i++)
if(!col[i]&&!dg[u+i]&&!udg[n-u+i]){
queens[u][i] = 'Q';
col[i] = dg[u+i] = udg[n-u+i] = true;
dfs(u+1, queens, res);
col[i] = dg[u+i] = udg[n-u+i] = false;
queens[u][i] = '.';
}
}
};
class Solution {
public:
int maxSubArray(vector& nums) {
int res = nums[0], cursum = 0;
for(auto x : nums){
cursum = max(cursum+x, x);
res = max(res, cursum);
}
return res;
}
};
class Solution {
public:
vector spiralOrder(vector>& matrix) {
if(matrix.empty()||matrix[0].empty()) return {};
int m = matrix.size(), n = matrix[0].size();
vector res;
int up = 0, down = m-1, left = 0, right = n-1;
while(true){
for(int j = left; j <= right; j++) res.push_back(matrix[up][j]);
if(++up > down) break;
for(int i = up; i <= down; i++) res.push_back(matrix[i][right]);
if(--right= left; j--) res.push_back(matrix[down][j]);
if(--down < up) break;
for(int i = down; i >= up; i-- ) res.push_back(matrix[i][left]);
if(++left>right) break;
}
return res;
}
};
class Solution{
public:
vector> merge(vector> &intervals){
if(intervals.empty()) return {};
sort(intervals.begin(), intervals.end());
vector> res = {intervals[0]};
for(int i=0; i
#include
using namespace std;
const int N=100000+100;
pair a[N];
int n,cnt;
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i].first>>a[i].second;
sort(a+1,a+1+n);
cnt=n;
for(int i=1;i=a[i+1].first)
{
cnt--;
a[i+1].first=a[i].first;
a[i+1].second=max(a[i+1].second,a[i].second);
}
cout<
class Solution {
public:
int uniquePaths(int m, int n) {
vector> f(m, vector(n, 0));
f[0][0] = 1;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i>0) f[i][j] += f[i-1][j];
if(j>0) f[i][j] += f[i][j-1];
}
}
return f[m-1][n-1];
}
};
class Solution {
public:
int minPathSum(vector>& grid) {
int m = grid.size(), n = grid[0].size();
int dp[m][n];
dp[0][0] = grid[0][0];
for(int i = 1; i < m; i++) dp[i][0] = grid[i][0]+dp[i-1][0];
for(int j = 1; j < n; j++) dp[0][j] = grid[0][j]+dp[0][j-1];
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}
}
return dp[m-1][n-1];
}
};
#include
#include
#include
using namespace std;
class Solution {
public:
int mySqrt(int x) {
if (x <= 1) return x;
int left = 0, right = x;
while (left < right) {
int mid = left + (right - left) / 2;
if (x / mid >= mid) left = mid + 1;
else right = mid;
}
return right - 1;
}
};
int main() {
int x = 8;
int res = Solution().mySqrt(x);
cout << res << endl;
system("pause");
return 0;
}
class Solution {
public:
int mySqrt(int x) {
int l = 0, r = x;
while(l < r){
int mid = l + r + 1 >> 1;
if(mid <= x / mid) l = mid;
else r = mid - 1;
}
return l;
}
};
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size(), n = word2.size();
vector> dp(m+1, vector(n+1));
for(int i = 0; i <= m; ++i) dp[i][0] = i;
for(int j = 0; j <= n; ++j) dp[0][j] = j;
for(int i = 1; i <= m; ++i)
for(int j = 1; j <= n; ++j){
if(word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1];
else dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1]))+1;
}
return dp[m][n];
}
};
class Solution {
public:
vector> ans;
vector> combine(int n, int k) {
vector path;
dfs(n, k, 1, path);
return ans;
}
void dfs(int n, int k, int t, vector path){
if(!k){
ans.push_back(path);
return;
}
for(int i = t; i <= n; i++){
path.push_back(i);
dfs(n, k-1, i+1, path);
path.pop_back();
}
}
};
#include
#include
using namespace std;
class Solution {
private:
void generation(int i, vector& nums, vector& item, vector>& result) {
if (i>=nums.size()) {
return;
}
item.push_back(nums[i]);
result.push_back(item);
generation(i + 1, nums, item, result);
item.pop_back();
generation(i + 1, nums, item, result);
}
public:
vector> subsets(vector& nums) {
vector item;
vector> result;
result.push_back(item);
generation(0, nums, item, result);
return result;
}
};
int main() {
vector nums;
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
vector> result = Solution().subsets(nums);
for (int i = 0; i < result.size(); i++) {
for (int j = 0; j < result[i].size(); j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
system("pause");
return 0;
}
#include
#include
using namespace std;
class Solution {
private:
void generation(int pos, vector& nums, vector& item, vector>& result) {
result.push_back(item);
for (int i = pos; i < nums.size(); i++) {
item.push_back(nums[i]);
generation(i + 1, nums, item, result);
item.pop_back();
}
}
public:
vector> subsets(vector& nums) {
vector item;
vector> result;
generation(0, nums, item, result);
return result;
}
};
int main() {
vector nums;
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
vector> result = Solution().subsets(nums);
for (int i = 0; i < result.size(); i++) {
for (int j = 0; j < result[i].size(); j++) {
cout <
public:
vector> subsets(vector& nums) {
vector> res;
for (int i = 0; i < 1 << nums.size(); i ++ )
{
vector now;
for (int j = 0; j < nums.size(); j ++ )
if (i >> j & 1)
now.push_back(nums[j]);
res.push_back(now);
}
return res;
}
};
#include
#include
#include
using namespace std;
class Solution {
public:
bool exist(vector>& board, string word) {
if (board.empty() || board[0].empty()) return false;
int m = board.size(), n = board[0].size();
vector> visited(m, vector(n));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (search(board, word, 0, i, j, visited)) return true;
}
}
return false;
}
bool search(vector>& board, string word, int idx, int i, int j, vector>& visited) {
if (idx == word.size()) return true;
int m = board.size(), n = board[0].size();
if (i < 0 || j < 0 || i >= m || j >= n || visited[i][j] || board[i][j] != word[idx]) return false;
visited[i][j] = true;
bool res = search(board, word, idx + 1, i - 1, j, visited)
|| search(board, word, idx + 1, i + 1, j, visited)
|| search(board, word, idx + 1, i, j - 1, visited)
|| search(board, word, idx + 1, i, j + 1, visited);
visited[i][j] = false;
return res;
}
};
int main() {
vector> board =
{
{'A', 'B', 'C', 'E'},
{'S', 'F', 'C', 'S'},
{'A', 'D', 'E', 'E'}
};
string word = "ABCCED";
bool res = Solution().exist(board, word);
cout << res << endl;
system("pause");
return 0;
}
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head) return head;
ListNode *p = head;
while(p->next){
if(p->val==p->next->val) p->next = p->next->next;
else p = p->next;
}
return head;
}
};
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int p1 = m-1, p2 = n-1, cur = m+n-1;
while(p1 >= 0 && p2 >= 0){
if(nums1[p1]<nums2[p2]) nums1[cur--] = nums2[p2--];
else nums1[cur--] = nums1[p1--];
}
if(p2>=0) for(int k = p2; k>=0; k--) nums1[cur--] = nums2[p2--];
}
};
#include
#include
#include
using namespace std;
class Solution {
public:
vector> subsetsWithDup(vector &S) {
if (S.empty()) return {};
vector> res;
vector out;
sort(S.begin(), S.end());
getSubsets(S, 0, out, res);
return res;
}
void getSubsets(vector &S, int pos, vector &out, vector> &res) {
res.push_back(out);
cout << endl;
for (int i = pos; i < S.size(); ++i) {
out.push_back(S[i]);
getSubsets(S, i + 1, out, res);
out.pop_back();
while (i + 1 < S.size() && S[i] == S[i + 1])
++i;
}
}
};
int main() {
vector nums = {2,1,2,2};
vector> result = Solution().subsetsWithDup(nums);
for (int i = 0; i < result.size(); i++) {
for (int j = 0; j < result[i].size(); j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
system("pause");
return 0;
}
#include
#include
#include
#include
using namespace std;
class Solution {
public:
vector restoreIpAddresses(string s) {
vector res;
restore(s, 4, "", res);
return res;
}
void restore(string s, int k, string out, vector &res) {
if (k == 0) {
if (s.empty()) res.push_back(out);
}
else {
for (int i = 1; i <= 3; ++i) {
if (s.size() >= i && isValid(s.substr(0, i))) {
if (k == 1) restore(s.substr(i), k - 1, out + s.substr(0, i), res);
else restore(s.substr(i), k - 1, out + s.substr(0, i) + ".", res);
}
}
}
}
bool isValid(string s) {
if (s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0')) return false;
int res = atoi(s.c_str());
return res <= 255 && res >= 0;
}
};
int main() {
string s = "25525511135";
vector result = Solution().restoreIpAddresses(s);
for (int i = 0; i < result.size(); i++) {
cout << result[i] << endl;
}
system("pause");
return 0;
}
class Solution {
public:
vector restoreIpAddresses(const string& s) {
vector result;
vector ip;
dfs(s, ip, result, 0);
return result;
}
void dfs(string s, vector& ip, vector &result, size_t start) {
if (ip.size() == 4 && start == s.size()) {
result.push_back(ip[0] + '.' + ip[1] + '.' + ip[2] + '.' + ip[3]);
return;
}
if (s.size() - start > (4 - ip.size()) * 3)
return;
if (s.size() - start < (4 - ip.size()))
return;
int num = 0;
for (size_t i = start; i < start + 3; i++) {
num = num * 10 + (s[i] - '0');
if (num < 0 || num > 255) continue;
ip.push_back(s.substr(start, i - start + 1));
dfs(s, ip, result, i + 1);
ip.pop_back();
if (num == 0) break;
}
}
};
class Solution {
public:
vector inorderTraversal(TreeNode* root) {
vector res;
stack s;
TreeNode *p = root;
while (!s.empty() || p) {
if (p) {
s.push(p);
p = p->left;
} else {
p = s.top(); s.pop();
res.push_back(p->val);
p = p->right;
}
}
return res;
}
};
class Solution {
public:
vector inorderTraversal(TreeNode *root) {
vector res;
inorder(root, res);
return res;
}
void inorder(TreeNode *root, vector &res) {
if (!root) return;
if (root->left) inorder(root->left, res);
res.push_back(root->val);
if (root->right) inorder(root->right, res);
}
};
class Solution {
public:
int numTrees(int n) {
vector dp(n+1);
dp[0] = dp[1] = 1;
for(int i =2; i<=n; i++)
for(int j = 0; j < i; j++)
dp[i] += dp[j]*dp[i-j-1];
return dp[n];
}
};
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL&&q==NULL)
return true;
if(p==NULL&&q!=NULL)
return false;
if(p!=NULL&&q==NULL)
return false;
return p->val==q->val&&isSameTree(p->left, q->left)&&isSameTree(p->right, q->right);
}
};
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return dfs(root->left, root->right);
}
bool dfs(TreeNode* p, TreeNode* q){
if(!p||!q) return !p&&!q;
if(p->val!=q->val) return false;
return dfs(p->left, q->right)&&dfs(p->right, q->left);
}
};
class Solution {
public:
int maxDepth(TreeNode* root) {
int ans = dfs(root);
return ans;
}
int dfs(TreeNode* root){
if(!root) return 0;
return max(dfs(root->left), dfs(root->right)) + 1;
}
};
class Solution {
public:
int maxDepth(TreeNode* root) {
int ans = dfs(root);
return ans;
}
int dfs(TreeNode* root){
if(!root) return 0;
int d1 = 0, d2 = 0;
if(root->left) d1 = dfs(root->left);
if(root->right) d2 = dfs(root->right);
return max(d1, d2) + 1;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
map hash;
vector preorder, inorder;
TreeNode* buildTree(vector& pre, vector& in) {
preorder = pre, inorder = in;
for(int i = 0; i < inorder.size(); i++) hash[inorder[i]] = i;
return dfs(0, preorder.size()-1, 0, inorder.size()-1);
}
TreeNode* dfs(int pl, int pr, int il, int ir){
if(pl>pr) return nullptr;
auto root = new TreeNode(preorder[pl]);
int k = hash[root->val];
auto left = dfs(pl+1, pl+k-il, il, k-1);
auto right = dfs(pl+k-il+1, pr, k+1, ir);
root->left = left, root->right = right;
return root;
}
};
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
queue<TreeNode*> q;
vector<vector<int>> ans;
if(!root) return ans;
vector<int> level;
q.push(root);
q.push(nullptr);
while(q.size()){
TreeNode* t = q.front();
q.pop();
if(!t){
ans.push_back(level);
level.clear();
if(q.back()) q.push(nullptr);
continue;
}
level.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
return vector<vector<int>>(ans.rbegin(), ans.rend());
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector& nums) {
return dfs(0, nums.size()-1, nums);
}
TreeNode* dfs(int l, int r, vector& nums){
if(l>r) return nullptr;
int mid = (l+r)/2;
TreeNode* root = new TreeNode(nums[mid]);
TreeNode* left = dfs(l, mid-1, nums);
TreeNode* right = dfs(mid+1, r, nums);
root->left = left, root->right = right;
return root;
}
};
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
if(!left||!right) return left+right+1;
return min(left, right)+1;
}
};
class Solution {
public:
vector> res;
vector> pathSum(TreeNode* root, int sum) {
vector path;
dfs(root, sum, 0, path);
return res;
}
void dfs(TreeNode* root, int sum, int curSum, vector& path){
if(!root) return;
path.push_back(root->val);
curSum += root->val;
if(curSum == sum&&!root->left&&!root->right) res.push_back(path);
dfs(root->left, sum, curSum, path);
dfs(root->right, sum, curSum, path);
path.pop_back();
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
TreeNode* now = root;
while(now){
if(now->left){
TreeNode* p = now->left;
while(p->right) p = p->right;
p->right = now->right;
now->right = now->left;
now->left = nullptr;
}
now = now->right;
}
}
};
class Solution {
public:
int maxProfit(vector& prices) {
int res = 0, buy = INT_MAX;
for (int price : prices) {
buy = min(buy, price);
res = max(res, price - buy);
}
return res;
}
};
class Solution {
public:
int maxProfit(vector& prices) {
int res = 0, n = prices.size();
for(int i = 0; i < n-1; i++){
if(prices[i]
class Solution {
public:
vector> st;
int n, m;
void solve(vector>& board) {
if(board.empty() || board[0].empty()) return;
n = board.size(), m = board[0].size();
for(int i = 0; i temp;
for(int j = 0; j>&board, int x, int y){
st[x][y] = true;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
for(int i = 0; i < 4; i++){
int a = x + dx[i], b = y + dy[i];
if(a >= 0 && a < n && b >= 0 && b < m && !st[a][b] && board[a][b] == 'O')
dfs(board, a, b);
}
}
};
如果原字符串是 abcd, 那么访问顺序为: a -> b -> c -> d -> cd -> bc -> bcd-> ab -> abc -> abcd, 这是对于没有两个或两个以上子回文串的情况。那么假如原字符串是 aabc,那么访问顺序为:a -> a -> b -> c -> bc -> ab -> abc -> aa -> b -> c -> bc -> aab -> aabc。
#include
#include
#include
using namespace std;
class Solution {
public:
vector> partition(string s) {
vector> res;
vector out;
helper(s, 0, out, res);
return res;
}
void helper(string s, int start, vector& out, vector>& res) {
if (start == s.size()) {
res.push_back(out);
return;
}
for (int i = start; i < s.size(); ++i) {
if (!isPalindrome(s, start, i)) continue;
out.push_back(s.substr(start, i - start + 1));
helper(s, i + 1, out, res);
out.pop_back();
}
}
bool isPalindrome(string s, int start, int end) {
while (start < end) {
if (s[start] != s[end]) return false;
++start; --end;
}
return true;
}
};
int main() {
string s = "aabc";
vector> res = Solution().partition(s);
for (int i = 0; i < res.size(); i++) {
for (int j = 0; j < res[i].size(); j++) {
cout << res[i][j] << " ";
}
}
system("pause");
return 0;
}
class Solution {
public:
int singleNumber(vector& nums) {
int res = 0;
for(auto x : nums) res ^=x;
return res;
}
};
class Solution {
public:
int singleNumber(vector& nums) {
int res = 0;
for(int i = 0; i < 32; i ++){
int sum = 0;
for(int j = 0; j < nums.size(); j++){
sum += (nums[j]>>i) & 1;
}
res |= (sum%3)<
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};
class Solution {
public:
vector preorderTraversal(TreeNode* root) {
vector res;
stack s;
TreeNode *p = root;
while (!s.empty() || p) {
if (p) {
s.push(p);
res.push_back(p->val);
p = p->left;
} else {
TreeNode *t = s.top(); s.pop();
p = t->right;
}
}
return res;
}
};
class Solution {
public:
vector postorderTraversal(TreeNode *root) {
vector res;
inorder(root, res);
return res;
}
void inorder(TreeNode *root, vector &res) {
if (!root) return;
if (root->left) inorder(root->left, res);
if (root->right) inorder(root->right, res);
res.push_back(root->val);
}
};
#include
#include
#include
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int data) : val(data), left(nullptr), right(nullptr) {}
};
void connectNode(TreeNode* pParent, TreeNode* left, TreeNode* right) {
if (pParent != nullptr){
pParent->left = left;
pParent->right = right;
}
}
class Solution {
public:
vector postorderTraversal(TreeNode* root) {
vector res;
stack s;
TreeNode *p = root;
while (!s.empty() || p) {
if (p) {
s.push(p);
res.insert(res.begin(), p->val);
p = p->right;
}
else {
TreeNode *t = s.top(); s.pop();
p = t->left;
}
}
return res;
}
};
int main() {
TreeNode* pNode1 = new TreeNode(1);
TreeNode* pNode2 = new TreeNode(2);
TreeNode* pNode3 = new TreeNode(3);
TreeNode* pNode4 = new TreeNode(4);
TreeNode* pNode5 = new TreeNode(5);
TreeNode* pNode6 = new TreeNode(6);
TreeNode* pNode7 = new TreeNode(7);
connectNode(pNode1, pNode2, pNode3);
connectNode(pNode2, pNode4, pNode5);
connectNode(pNode3, nullptr, pNode6);
connectNode(pNode5, pNode7, nullptr);
vector res = Solution().postorderTraversal(pNode1);
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
class Solution {
public:
vector postorderTraversal(TreeNode *root) {
vector res;
inorder(root, res);
return res;
}
void inorder(TreeNode *root, vector &res) {
if (!root) return;
if (root->left) inorder(root->left, res);
if (root->right) inorder(root->right, res);
res.push_back(root->val);
}
};
#include
#include
#include
using namespace std;
class Solution {
public:
int findMin(vector &num) {
int left = 0, right = num.size() - 1;
if (num[left] > num[right]) {
while (left != (right - 1)) {
int mid = (left + right) / 2;
if (num[left] < num[mid]) left = mid;
else right = mid;
}
return min(num[left], num[right]);
}
return num[0];
}
};
int main() {
vector nums = { 4,5,6,7,0,1,2 };
int result = Solution().findMin(nums);
cout << result << endl;
system("pause");
return 0;
}
#include
#include
#include
using namespace std;
class Solution {
public:
int findMin(vector &nums) {
if (nums.empty()) return 0;
int left = 0, right = nums.size() - 1, res = nums[0];
while (left < right - 1) {
int mid = left + (right - left) / 2;
if (nums[left] < nums[mid]) {
res = min(res, nums[left]);
left = mid + 1;
}
else if (nums[left] > nums[mid]) {
res = min(res, nums[right]);
right = mid;
}
else ++left;
}
res = min(res, nums[left]);
res = min(res, nums[right]);
return res;
}
};
int main() {
vector nums = { 10,1,10,10,10 };
int result = Solution().findMin(nums);
cout << result << endl;
system("pause");
return 0;
}
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (!headA || !headB) return NULL;
ListNode *a = headA, *b = headB;
while (a != b) {
a = a ? a->next : headB;
b = b ? b->next : headA;
}
return a;
}
};
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int m = dungeon.size(), n = dungeon[0].size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));
dp[m][n - 1] = 1; dp[m - 1][n] = 1;
for (int i = m - 1; i >= 0; --i) {
for (int j = n - 1; j >= 0; --j) {
dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
//cout << "i:" << i << "j:" << j << "dp:" << dp[i][j] << endl;
}
}
return dp[0][0];
}
};
class Solution {
public:
int n, m;
int numIslands(vector>& grid) {
if(grid.empty() || grid[0].empty()) return 0;
n = grid.size(), m = grid[0].size();
int res = 0;
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < m; j++){
if(grid[i][j] == '1'){
res++;
dfs(grid,i,j);
}
}
}
return res;
}
void dfs(vector>& grid, int x, int y){
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
grid[x][y] = '0';
for(int i = 0; i < 4; i++){
int a = x + dx[i], b = y + dy[i];
if(a >= 0 && a < n && b >= 0 && b < m && grid[a][b] == '1')
dfs(grid, a, b);
}
}
};
class Solution {
public:
int res = 0;
int numIslands(vector>& grid) {
if(grid.empty()||grid[0].empty()) return 0;
int m = grid.size(), n = grid[0].size();
vector> visited(m, vector(n));
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++){
//visited[i][j] = true;
if(grid[i][j] == '0' || visited[i][j]) continue;
dfs(grid, visited, i, j);
++res;
}
return res;
}
void dfs(vector>& grid, vector>& visited, int x, int y){
visited[x][y] = true;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
for(int k = 0; k < 4; k++){
int a = x + dx[k], b = y + dy[k];
if(a>=0&&a=0&&b
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.empty()) return 0;
int n = grid.size(), m = grid[0].size();
int cnt = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(grid[i][j]-'0' == 1){
cnt++;
dfs(i, j, grid);
}
return cnt;
}
void dfs(int i, int j, vector<vector<char>>& grid){
int n = grid.size(), m = grid[0].size();
grid[i][j] = '0';
if(i!=0 && grid[i-1][j] - '0'== 1) dfs(i-1, j, grid);
if(j!=m-1 && grid[i][j+1] - '0' == 1) dfs(i, j+1, grid);
if(i!=n-1 && grid[i+1][j] - '0' == 1) dfs(i+1, j, grid);
if(j!=0 && grid[i][j-1] - '0' == 1) dfs(i, j-1, grid);
return;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head){
return nullptr;
}
ListNode* first = head;//始终指向原链表的首位元素
ListNode* target = head->next;//始终指向即将要放到当前链表首元素之前的目标元素
while(target != nullptr){
first->next = target->next;
ListNode* temp = target->next;
target->next = head;
head = target;
target = temp;
}
return head;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* post = NULL;
while(cur!=NULL){
post = cur->next;
cur->next = pre;
pre = cur;
cur = post;
}
return pre;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
auto cur = head;
while(cur){
auto temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
class Solution {
public:
bool containsDuplicate(vector& nums) {
unordered_map h;
for(int i = 0; i < nums.size(); i++){
if(++h[nums[i]]>1) return true;
}
return false;
}
};
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
return dfs(root, k);
}
int dfs(TreeNode* root, int& k){
if(!root) return -1;
int val = dfs(root->left, k);
if(k == 0) return val;
if(--k == 0) return root->val;
return dfs(root->right, k);
}
};
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode* cur = head;
stackst;
while(cur){
st.push(cur->val);
cur = cur->next;
}
while(head){
int t = st.top(); st.pop();
if(head->val!=t) return false;
head = head->next;
}
return true;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return nullptr;
if(root==p||root==q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left&&right) return root;
if(left) return left;
else return right;
}
};
class Solution {
public:
vector maxSlidingWindow(vector& nums, int k) {
vector res;
multiset st;
for(int i = 0; i < nums.size(); i++){
if(i>=k) st.erase(st.find(nums[i-k]));
st.insert(nums[i]);
if(i>=k-1) res.push_back(*st.rbegin());
}
return res;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector ans;
vector binaryTreePaths(TreeNode* root) {
string path;
dfs(root, path);
return ans;
}
void dfs(TreeNode* root, string path){
if(!root) return;
if(!root->left && !root->right) {
ans.push_back(path+to_string(root->val));
return;
}
if(root->left) dfs(root->left, path+to_string(root->val)+"->");
if(root->right) dfs(root->right, path+to_string(root->val)+"->");
}
};
class Solution {
public:
bool isUgly(int num) {
if (num <= 0)
return false;
while (num % 5 == 0)
num = num / 5;
while (num % 3 == 0)
num = num / 3;
while (num % 2 == 0)
num = num / 2;
return num == 1;
}
};
class Solution {
public:
int nthUglyNumber(int n) {
vector uglyNumbers;
uglyNumbers.push_back(1);
int index2 = 0;//2 3 5三个指针
int index3 = 0;
int index5 = 0;
for(int i = 1;i
class Solution {
public:
int hIndex(vector& citations) {
int l = 0, r = citations.size();
while(l < r){
int mid = l+r+1ll >>1;
if(citations[citations.size()-mid] >= mid) l = mid;
else r = mid - 1;
}
return l;
}
};
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int l = 0, r = n;
while(l < r){
int mid = l + (r-l>>2);
if(isBadVersion(mid) == true) r = mid;
else l = mid+1;
}
return l;
}
};
class Solution {
public:
int numSquares(int n) {
queue q;
vector dist(n+1, -1);
q.push(0);
dist[0]=0;
while (q.size()){
int t = q.front();
q.pop();
if(t==n) return dist[t];
for(int i = 1; i*i+t<=n; i++){
int j = t+i*i;
if(dist[j] == -1){
dist[j] = dist[t] + 1;
q.push(j);
}
}
}
return 0;
}
};
class Solution {
public:
bool isAdditiveNumber(string num) {
for(int i = 1; i < num.size(); i++){
string s1 = num.substr(0, i);
if(s1.size() > 1 && s1[0] == '0') break;
for(int j = i + 1; j < num.size(); j++){
string s2 = num.substr(i, j-i);
long d1 = stol(s1), d2 = stol(s2);
if(s2.size()>1&&s2[0] == '0') break;
long next = d1 + d2;
string nextStr = to_string(next);
if(nextStr!=num.substr(j, nextStr.length())) continue;
string allStr = s1 + s2 + nextStr;
while(allStr.size() < num.size()){
d1 = d2;
d2 = next;
next = d1+d2;
nextStr = to_string(next);
allStr += nextStr;
}
if(allStr == num) return true;
}
}
return false;
}
};
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
int res = 0;
vector path;
dfs(root, sum, 0, path, res);
return res;
}
void dfs(TreeNode* root, int sum, int curSum, vector& path, int& res){
if(!root) return;
curSum += root->val;
path.push_back(root);
if(curSum == sum) ++res;
int t = curSum;
for(int i = 0; i < path.size()-1; i++){
t -= path[i]->val;
if(t == sum) ++res;
}
dfs(root->left, sum, curSum, path, res);
dfs(root->right, sum, curSum, path, res);
path.pop_back();
}
};
class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
int n = matrix.size(), m = matrix[0].size();
int res = INT_MIN;
vector<vector<int>> f(n+1, vector<int>(m+1));
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++){
f[i][j] = f[i-1][j]+f[i][j-1]-f[i-1][j-1] + matrix[i-1][j-1];
//cout << "f["<
}
for(int x2 = 1; x2 <= n; x2++)
for(int y2 = 1; y2 <= m; y2++)
for(int x1 = 1; x1 <= x2; x1++)
for(int y1 = 1; y1 <= y2; y1++){
int temp;
temp = f[x2][y2] - f[x1 - 1][y2] - f[x2][y1 - 1] + f[x1 - 1][y1 - 1];
//cout << "temp:"<
if(temp <= k) res = max(res, temp);
}
return res;
}
};
class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
int row = matrix.size();
if(!row) return 0;
int col = matrix[0].size();
if(!col) return 0;
int ret = INT_MIN;
for(int i=0; i<col; ++i) {
vector<int> sum(row, 0);
for(int j=i; j<col; ++j) {
for(int r=0; r<row; ++r) sum[r] += matrix[r][j];
int curSum = 0, curMax = INT_MIN;
set<int> sumSet;
sumSet.insert(0);
for(int r=0; r<row; ++r) {
curSum += sum[r];
auto it = sumSet.lower_bound(curSum-k);
if(it != sumSet.end()) curMax = max(curMax, curSum-*it);
sumSet.insert(curSum);
}
ret = max(ret, curMax);
}
}
return ret;
}
};
class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
if (matrix.empty() || matrix[0].empty()) return 0;
const int m = matrix.size(), n = matrix[0].size();
int res = INT_MIN;
for (int row1=0; row1<m; ++row1){
vector<int> sum(n, 0);
for (int row2=row1; row2<m; ++row2){
for (int col=0; col<n; ++col){
sum[col] += matrix[row2][col];
if (sum[col] == k) return k;
}
int curr_sum = 0, curr_max = INT_MIN;
for (int temp_s : sum){
curr_sum += temp_s;
if (curr_sum == k) return k;
if (curr_sum < k && curr_sum > res) res = curr_sum;
if (curr_sum < 0) curr_sum = 0;
}
if (curr_sum < k) continue;
curr_sum = 0;
set<int> sum_set{0};
for (int temp_s : sum){
curr_sum += temp_s;
auto it = sum_set.lower_bound(curr_sum - k);
if (it != sum_set.end()){
if (*it == curr_sum - k) return k;
if (curr_sum - *it > res)
res = curr_sum - *it;
}
sum_set.insert(curr_sum);
}
}
}
return res;
}
};
class Solution {
public:
Solution(ListNode* head) {
this->head = head;
}
int getRandom() {
int res = head->val, i = 2;
ListNode *cur = head->next;
while (cur) {
int j = rand() % i;
if (j == 0) res = cur->val;
++i;
cur = cur->next;
}
return res;
}
private:
ListNode *head;
};
class Solution {
public:
string addStrings(string num1, string num2) {
string res = "";
int carry = 0;
int m = num1.size(), n = num2.size();
int i = m-1, j = n-1;
while(i>=0||j>=0){
int a = i>=0 ? num1[i--]-'0' : 0;
int b = j>=0 ? num2[j--]-'0' : 0;
int sum = a + b + carry;
res.insert(res.begin(), sum % 10 + '0');
carry = sum/10;
}
return carry ? '1'+res : res;
}
};
class Solution {
public:
bool canPartition(vector& nums) {
int sum = accumulate(nums.begin(), nums.end(), 0);
const int N = nums.size();
int target = sum >> 1;
if (sum % 2 != 0) return false;
//dp[i][j] means whether we can sum to j using first i numbers.
vector> dp(N + 1, vector(sum + 1, false));
// every number can build number 0.
for (int i = 0; i <= N; ++i) {
dp[i][0] = true;
}
// but for position 0, it can build number nothing.
for (int j = 1; j <= target; ++j) {
dp[0][j] = false;
}
// anyway, position 0 can build number 0.
dp[0][0] = true;
for (int i = 1; i <= N; ++i) {
for (int j = 0; j <= target; ++j) {
if (j >= nums[i - 1])
dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]];
else
dp[i][j] = dp[i - 1][j];
}
}
return dp[N][target];
}
};
class Solution {
public:
bool canPartition(vector& nums) {
int sum = accumulate(nums.begin(), nums.end(), 0), target = sum >> 1;
if(sum & 1) return false;
vector dp(target+1, false);
dp[0] = true;
for(int num:nums){
for(int i = target; i >= num; i--){
dp[i] = dp[i]||dp[i-num];
}
}
return dp[target];
}
};
class Solution {
public:
int compress(vector<char>& chars){
int n = chars.size();
int count = 1;
vector<char> res;
res.push_back(chars[0]);
for(int i = 1; i < n; i++){
if(chars[i] == chars[i-1]){
count++;
continue;
}
if(count != 1){
if(count/10) res.push_back(count/10+'0');
res.push_back(count%10+'0');
}
res.push_back(chars[i]);
count = 1;
}
if(count != 1) {
if(count/10) res.push_back(count/10+'0');
res.push_back(count%10+'0');
}
for(int i = 0; i < res.size(); i++){
chars[i] = res[i];
}
return res.size();
}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack s1, s2;
while(l1){
s1.push(l1->val);
l1 = l1->next;
}
while(l2){
s2.push(l2->val);
l2 = l2->next;
}
int sum = 0;
ListNode* res = new ListNode(0);
while(!s1.empty()||!s2.empty()){
if(!s1.empty()) {sum += s1.top(); s1.pop();}
if(!s2.empty()) {sum += s2.top(); s2.pop();}
res->val = sum % 10;
ListNode* head = new ListNode(sum/10);
head->next = res;
res = head;
sum /= 10;
}
return res->val == 0 ? res->next:res;
}
};
class Solution {
public:
bool find132pattern(vector& nums) {
int n = nums.size(), mn = INT_MAX;
for(int j = 0; j < n; j++){
mn = min(mn, nums[j]);
if(mn == nums[j]) continue;
for(int k = n-1; k >= j; k--){
if(mn < nums[k] && nums[j] > nums[k]) return true;
}
}
return false;
}
};
class Solution {
public:
int findMaxForm(vector& strs, int m, int n) {
vector> dp(m+1, vector(n+1, 0));
for(string str : strs){
int zeros = 0, ones = 0;
for(char c : str)(c == '0') ? ++zeros : ++ones;
for(int i = m; i >= zeros; i--){
for(int j = n; j >= ones; j--){
dp[i][j] = max(dp[i][j], dp[i-zeros][j-ones]+1);
}
}
}
return dp[m][n];
}
};
class Solution {
public:
int fib(int N) {
if(N==0)
return 0;
if(N==1)
return 1;
return fib(N-1)+fib(N-2);
}
};
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
int ans = 0;
dfs(root, ans);
return ans;
}
int dfs(TreeNode *r, int &ans){
if(r == NULL) return -1;
int d1 = dfs(r->left, ans);
int d2 = dfs(r->right, ans);
ans = max(ans, d1+d2+2);
return max(d1, d2)+1;
}
};
class MyLinkedList {
public:
MyLinkedList() {
head = NULL;
size = 0;
}
int get(int index) {
if (index < 0 || index >= size) return -1;
Node *cur = head;
for (int i = 0; i < index; ++i) cur = cur->next;
return cur->val;
}
void addAtHead(int val) {
Node *t = new Node(val, head);
head = t;
++size;
}
void addAtTail(int val) {
Node *cur = head;
while (cur->next) cur = cur->next;
cur->next = new Node(val, NULL);
++size;
}
void addAtIndex(int index, int val) {
if (index > size) return;
if (index <= 0) {addAtHead(val); return;}
Node *cur = head;
for (int i = 0; i < index - 1; ++i) cur = cur->next;
Node *t = new Node(val, cur->next);
cur->next = t;
++size;
}
void deleteAtIndex(int index) {
if (index < 0 || index >= size) return;
if (index == 0) {
head = head->next;
--size;
return;
}
Node *cur = head;
for (int i = 0; i < index - 1; ++i) cur = cur->next;
cur->next = cur->next->next;
--size;
}
private:
struct Node {
int val;
Node *next;
Node(int x, Node* n): val(x), next(n) {}
};
Node *head, *tail;
int size;
};
class Solution {
public:
int findLength(vector& A, vector& B) {
int m = A.size(), n = B.size();
int dp[m][n];
int res = 0;
for(int i = 0; i < m; i++) dp[i][0] = A[i] == B[0] ? 1 : 0;
for(int j = 0; j < n; j++) dp[0][j] = A[0] == B[j] ? 1 : 0;
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
dp[i][j] = A[i] == B[j] ? dp[i-1][j-1] + 1 : 0;
res = max(res, dp[i][j]);
}
}
return res;
}
};
class Solution {
public:
vector> floodFill(vector>& image, int sr, int sc, int newColor) {
if(image.empty()||image[0].empty()) return image;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int oldColor = image[sr][sc];
if(oldColor == newColor) return image;
image[sr][sc] = newColor;
for(int i = 0; i<4; i++ ){
int x = sr + dx[i], y = sc + dy[i];
if(x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oldColor)
floodFill(image, x, y, newColor);
}
return image;
}
};
class Solution {
public:
vector ans;
vector letterCasePermutation(string S) {
dfs(S, 0);
return ans;
}
void dfs(string S, int t){
if(t==S.size()) {
ans.push_back(S);
return;
}
dfs(S, t+1);
if(S[t]>='A'){
S[t]^=32;
dfs(S, t+1);
}
}
};
#include
#include
using namespace std;
class Solution {
public:
int minAddToMakeValid(string S) {
int len = S.length();
int first = 0, last = 0; //first记录反括号数量,last记录括号数量
for (int i = 0; i < len; i++) {
if (S[i] == '(')last++;
else {
if (last == 0)first++;
else last--;
}
}
return first + last;
}
};
int main() {
string S = "(((";
int result = Solution().minAddToMakeValid(S);
cout << result << endl;
system("pause");
}
class Solution {
public:
int numSubmatrixSumTarget(vector>& matrix, int target) {
int n = matrix.size(), m = matrix[0].size();
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = 1; j < m; j++)
matrix[i][j] += matrix[i][j - 1];
for (int l = 0; l < m; l++)
for (int r = l; r < m; r++) {
unordered_map vis;
vis[0] = 1;
int tot = 0;
for (int k = 0; k < n; k++) {
if (l == 0) {
tot += matrix[k][r];
} else {
tot += matrix[k][r] - matrix[k][l - 1];
}
if (vis.find(tot - target) != vis.end())
ans += vis[tot - target];
vis[tot]++;
}
}
return ans;
}
};
class Solution {
public:
vector<int> createTargetArray(vector<int>& nums, vector<int>& index) {
int n = nums.size();
vector<int> target(n);
int trail = -1;
for(int i = 0; i < n; i++){
trail++;
for(int j = trail; j>index[i]; j--){
target[j] = target[j-1];
}
target[index[i]]=nums[i];
}
return target;
}
};
class Solution {
public:
int sumFourDivisors(vector<int>& nums) {
int n = nums.size();
int ans = 0;
for(int i = 0; i < n; i++){
int k = nums[i];
int cnt = 0;
int sum = 0;
for(int j = 1; j <= sqrt(k); j++){
if(k%j == 0) {
sum += j, cnt++;
if(k/j != j) sum += k/j, cnt++;
}
}
if(cnt == 4) ans += sum;
}
return ans;
}
};