You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
introb(vector<int> &nums) { int n=nums.size(); int pre=cur=0; for(int i=0; i<n; i++) { int temp = max(pre+nums[i], cur); pre = cur; cur = temp; } return cur; }
740. Delete and Earn
Description:
Given an array nums of integers, you can perform operations on the array.
In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
Example 1:
1 2 3 4 5 6
Input: nums = [3, 4, 2] Output: 6 Explanation: Delete 4 to earn 4 points, consequently 3 is also deleted. Then, delete 2 to earn 2 points. 6 total points are earned.
Example 2:
1 2 3 4 5 6 7
Input: nums = [2, 2, 3, 3, 3, 4] Output: 9 Explanation: Delete 3 to earn 3 points, deleting both 2's and the 4. Then, delete 3 again to earn 3 points, and 3 again to earn 3 points. 9 total points are earned.
Note:
The length of nums is at most 20000.
Each element nums[i] is an integer in the range [1, 10000].
解题思路:此题本质上是house robber问题,参考上题,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intdeleteAndEarn(vector<int>& nums){ vector<int> hash(10001,0); for(int n :nums) hash[n]+=n; int pre=0, cur=0; for(int i=0; i<10001; i++){ int temp=cur; cur=max(pre+hash[i],cur); pre=temp; } return cur; } };
64. Minimum Path Sum
Description:Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example 1:
1 2 3 4
[[1,3,1], [1,5,1], [4,2,1]]
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
1 2 3 4 5 6
Input: s1 = "sea", s2 = "eat" Output: 231 Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum. Deleting "t" from "eat" adds 116 to the sum. At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
Example 2:
1 2 3 4 5 6 7
Input: s1 = "delete", s2 = "leet" Output: 403 Explanation: Deleting "dee" from "delete" to turn the string into "let", adds 100[d]+101[e]+101[e] to the sum. Deleting "e" from "leet" adds 101[e] to the sum. At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403. If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
Note:
0 < s1.length, s2.length <= 1000.
All elements of each string will have an ASCII value in [97, 122].
classSolution { public: intcountSubstrings(string s){ int res = 0, n = s.length(); for(int i = 0; i < n; i++){ for(int j = 0; i-j >= 0 && i+j < n && s[i-j] == s[i+j]; j++)res++; for(int j = 0; i-1-j >= 0 && i+j < n && s[i-1-j] == s[i+j]; j++)res++; } return res; } };
467. Unique Substrings in Wraparound String
Description:
Consider the string s to be the infinite wraparound string of “abcdefghijklmnopqrstuvwxyz”, so s will look like this: “…zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd….”.
Now we have another string p. Your job is to find out how many unique non-empty substrings of p are present in s. In particular, your input is the string p and you need to output the number of different non-empty substrings of p in the string s.
Note:p consists of only lowercase English letters and the size of p might be over 10000.
Example 1:
1 2 3 4 5
Input: "a" Output: 1
Explanation: Only the substring "a" of string "a" is in the string s.
Example 2:
1 2 3 4
Input: "cac" Output: 2 Explanation: There are two substrings "a", "c" of string "cac" in the string s.
Example 3:
1 2 3
Input: "zab" Output: 6 Explanation: There are six substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in the string s.
Initially on a notepad only one character ‘A’ is present. You can perform two operations on this notepad for each step:
Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
Paste: You can paste the characters which are copied last time.
Given a number n. You have to get exactlyn ‘A’ on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n ‘A’.
Example 1:
1 2 3 4 5 6 7 8
Input: 3 Output: 3 Explanation: Intitally, we have one character 'A'. In step 1, we use Copy All operation. In step 2, we use Paste operation to get 'AA'. In step 3, we use Paste operation to get 'AAA'.
classSolution { public: intfindMaxForm(vector<string>& strs, int m, int n){ vector<vector<int>> res(m+1, vector<int>(n+1, 0)); for(auto &s : strs){ int cZeros=0, cOnes=0; for(auto c : s){ if(c=='0') cZeros++; elseif(c=='1') cOnes++; } for(int i=m; i>=cZeros; i--){ for(int j=n; j>=cOnes; j--){ res[i][j]=max(res[i][j], res[i-cZeros][j-cOnes]+1); } } } return res[m][n]; } };
486. Predict the Winner
Description:
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example 1:
1 2 3 4 5 6 7
Input: [1, 5, 2] Output: False Explanation: Initially, player 1 can choose between 1 and 2. If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence, player 1 will never be the winner and you need to return False.
Example 2:
1 2 3 4 5
Input: [1, 5, 233, 7] Output: True Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
1 <= length of the array <= 20.
Any scores in the given array are non-negative integers and will not exceed 10,000,000.
If the scores of both players are equal, then player 1 is still the winner.
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:
1 2 3 4 5 6
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
1 2 3 4 5
Input: [1, 2, 3, 5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
classSolution { public: boolcanPartition(vector<int>& nums){ int n = nums.size(); int sum = 0; for(int num : nums) sum+=num; if((sum&1)==1) returnfalse; sum /= 2; vector<vector<bool>> dp(n+1, vector<bool>(sum+1, false)); dp[0][0]=true; for(int i=1; i<n+1; i++) dp[i][0]=true; for(int j=1; j<sum+1; j++) dp[0][j]=false; for(int i=1; i<n+1; i++){ for(int j=1; j<sum+1; j++){ dp[i][j]=dp[i-1][j]; if(j>=nums[i-1]) dp[i][j]=dp[i][j] || dp[i-1][j-nums[i-1]]; } } return dp[n][sum]; } boolcanPartition2(vector<int>& nums){ int n = nums.size(); int sum = 0; for(int num : nums) sum+=num; if((sum&1)==1) returnfalse; sum /= 2; vector<bool> dp(sum+1, false); dp[0]=true; for(int num : nums){ for(int i=sum; i>=num; i--){ dp[i]=dp[i]||dp[i-num]; } } return dp[sum]; } };
494. Target Sum
Description:
You are given a list of non-negative integers, a1, a2, …, an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12
Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation:
There are 5 ways to assign symbols to make the sum of nums be target 3.
Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
代码如下:此题套了上一题的dp,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intfindTargetSumWays(vector<int>& nums, int S){ int sum=0; for(int num : nums) sum+=num; return sum<S||(S+sum)%2>0?0:subsetSum(nums, (S+sum)>>1); } intsubsetSum(vector<int> &nums, int target){ vector<int> dp(target+1, 0); dp[0]=1; for(int num : nums){ for(int i=target; i>=num; i--) dp[i]+=dp[i-num]; } return dp[target]; } };
139. Word Break
Description:
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.
For example, given s = "leetcode", dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
UPDATE (2017/1/4): The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
714. Best Time to Buy and Sell Stock with Transaction Tree
Description:
Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
Return the maximum profit you can make.
Example 1:
1 2 3 4 5
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2 Output: 8 Explanation: The maximum profit can be achieved by: Buying at prices[0] = 1Selling at prices[3] = 8Buying at prices[4] = 4Selling at prices[5] = 9The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number, and ndoes not exceed 1690.
Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Input: S = "rabbbit", T = "rabbit" Output: 3 Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S. (The caret symbol ^ means the chosen letters)
rabbbit ^^^^ ^^ rabbbit ^^ ^^^^ rabbbit ^^^ ^^^
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Input: S = "babgbag", T = "bag" Output: 5 Explanation:
As shown below, there are 5 ways you can generate "bag" from S. (The caret symbol ^ means the chosen letters)
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
1 2 3 4 5 6 7 8 9
Input: s = "catsanddog" wordDict = ["cat", "cats", "and", "sand", "dog"] Output: [ "cats and dog", "cat sand dog" ]
Example 2:
1 2 3 4 5 6 7 8 9 10 11
Input: s = "pineapplepenapple" wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] Output: [ "pine apple pen apple", "pineapple pen apple", "pine applepen apple" ] Explanation: Note that you are allowed to reuse a dictionary word.
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0’s) or contain magic orbs that increase the knight’s health (positive integers).
In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Write a function to determine the knight’s minimum initial health so that he is able to rescue the princess.
For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
-2 (K)
-3
3
-5
-10
1
10
30
-5 (P)
Note:
The knight’s health has no upper bound.
Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
usingnamespace std; classSolution { public: intcalculateMinimumHP(vector<vector<int>>& dungeon){ int m = dungeon.size(); int n = dungeon[0].size(); vector<vector<int>> hp(m+1, vector<int>(n+1, INT_MAX)); hp[m][n-1]=1; hp[m-1][n]=1; for(int i=m-1;i>=0; i--){ for(int j=n-1;j>=0;j--){ int need = min(hp[i+1][j],hp[i][j+1])-dungeon[i][j]; hp[i][j]=need<=0?1:need; } } return hp[0][0]; } };
188. Best Time to Buy and Sell Stock IV
Description:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example 1:
1 2 3 4
Input: [2,4,1], k = 2 Output: 2 Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
1 2 3 4
Input: [3,2,6,5,0,3], k = 2 Output: 7 Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
#include<stdio.h> #include<string> #include<stack> #include<vector> usingnamespace std; classSolution { public: intlongestValidParentheses(string s){ int len = s.length(), res = 0; stack<int> st; for(int i=0; i<len; i++){ if(s[i]=='(') st.push(i); else{ if(!st.empty() && s[st.top()]=='(') st.pop(); else st.push(i); } } if(st.empty()) return len; int a=len, b=0; while(!st.empty()){ b=st.top(); st.pop(); res = max(res, a-b-1); a=b; } res = max(res,a); return res; } intlongestValidParentheses2(string s){ int len = s.length(), res=0; vector<int> dp(len, 0); for(int i=1;i<len;i++){ if(s[i]==')' && i-dp[i-1]-1>=0 && s[i-dp[i-1]-1]=='('){ dp[i]=dp[i-1] + 2 + ((i-dp[i-1]-2>=0)?dp[i-dp[i-1]-2]:0); res = max(dp[i],res); } } return res; } };
62. Unique Paths
Description:
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note:m and n will be at most 100.
Example 1:
1 2 3 4 5 6 7 8
Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right