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.
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
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
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
[[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.
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
Input: "a"
Output: 1
Explanation: Only the substring "a" of string "a" is in the string s.
Example 2:
1
2
3
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.
代码如下：
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
classSolution {
public:
intfindSubstringInWraproundString(string p){
vector<int> count(26);
int maxLenCur=0;
for(int i=0; i<p.size(); i++){
if(i>0 && (p[i]-p[i-1]==1 || p[i-1]-p[i]==25)){
maxLenCur++;
}else{
maxLenCur=1;
}
int index=p[i]-'a';
count[index]=max(count[index],maxLenCur);
}
int sum=0;
for(int n : count) sum+=n;
return sum;
}
};
95. Unique Binary Search Trees II
Description:
Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1…n.
For example,
Given n = 3, your program should return all 5 unique BST’s shown below.
1
2
3
4
5
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
代码如下：
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
classSolution{
public:
vector<TreeNode*> generateTrees(int n){
if(n==0) returnvector<TreeNode*> {NULL};
return generator(1, n);
}
vector<TreeNode*> generator(int start, int end){
if(start>end) returnvector<TreeNode*> {NULL};
vector<TreeNode*> res;
for(int i=start; i<=end; i++){
vector<TreeNode*> l = generator(start, i-1);
vector<TreeNOde*> r = generator(i+1, end);
for(int j=0; j<l.size();j++){
for(int k=0; k<r.size();k++){
TreeNode* root = new TreeNode(i);
root->left = l[j];
root->right = r[k];
res.push_back(root);
}
}
}
return res;
}
}
96. Unique Binary Search Trees
Description:
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?
For example,
Given n = 3, there are a total of 5 unique BST’s.
1
2
3
4
5
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
代码如下：
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
public:
intnumTrees(int n){
vector<int> res(n+1);
res[0]=res[1]=1;
for(int i=2; i<=n; i++){
for(int j=1; j<=i; j++){
res[i]+=res[j-1]*res[i-j];
}
}
return res[n];
}
};
120. Triangle
Description:
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
1
2
3
4
5
6
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
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
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'.
Note:
The n will be in the range [1, 1000].
代码如下：
1
2
3
4
5
6
7
8
9
classSolution {
public:
intminSteps(int n){
if(n==1) return0;
for(int i=2; i<n; i++)
if(n%i==0) return i+minSteps(n/i);
return n;
}
};
474. Ones and Zeros
Description:
In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m0s and n1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.
Now your task is to find the maximum number of strings that you can form with given m0s and n1s. Each 0 and 1 can be used at most once.
Note:
The given numbers of 0s and 1s will both not exceed 100
The size of given string array won’t exceed 600.
Example 1:
1
2
3
4
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4
Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”
Example 2:
1
2
3
4
Input: Array = {"10", "0", "1"}, m = 1, n = 1
Output: 2
Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".
解题思路：此题明显是一道dp题，本题适合二维矩阵，代码如下：
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
classSolution {
public:
intfindMaxForm(vector<string>& strs, int m, int n){
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
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
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
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.
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
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
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.
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
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.
Note:
0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.
代码如下：
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
public:
intmaxProfit(vector<int>& prices, int fee){
long t_ik0=0, t_ik1=INT_MIN;
for(int price : prices){
long t_ik0_old = t_ik0;
t_ik0 = max(t_ik0, t_ik1+price-fee);
t_ik1 = max(t_ik1, t_ik0_old-price);
}
return t_ik0;
}
};
152. Maximum Product Subarray
Description:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
代码如下：
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
public:
intmaxProduct(vector<int>& nums){
int n = nums.size();
if(n==1) return nums[0];
int pMax=0, nMax=0, m=0;
for(int i=0; i<n; i++){
if(nums[i]<0) swap(pMax, nMax);
pMax=max(pMax*nums[i], nums[i]);
nMax=min(nMax*nums[i], nums[i]);
if(pMax>m) m = pMax;
}
return m;
}
};
516. Longest Palindromic Subsequence
Description:
Given a string s, find the longest palindromic subsequence’s length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
1
"bbbab"
Output:
1
4
One possible longest palindromic subsequence is “bbbb”.
Example 2:
Input:
1
"cbbd"
Output:
1
2
One possible longest palindromic subsequence is “bb”.
解题思路：字符串=>网格，代码如下：
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
public:
intlongestPalindromeSubseq(string s){
int len = s.length();
if(len==0) return0;
vector<vector<int>> dp(len, vector<int>(len,0));
for(int i=len-1; i>=0; i--){
dp[i][i]=1;
for(int j=i+1; j<len; j++){
if(s[i]==s[j]) dp[i][j]=dp[i+1][j-1]+2;
else dp[i][j]=max(dp[i+1][j],dp[i][j-1]);
}
}
return dp[0][len-1];
}
};
221. Maximal Square
Description:
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.
For example, given the following matrix:
1
2
3
4
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
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.