. You will be given the number of pairs of parenthesis. Find out the total possible valid unique combinations and there should not be any duplicity. Write code
这个应该有计算公式吧???
. You will be given the number of pairs of parenthesis. Find out the total possible valid unique combinations and there should not be any duplicity. Write code
这个应该有计算公式吧???
private static int numberOf1Bits(int n) {
int mask = 0; // set the mask as the left part of nPlusOne
int nBits = 0; // counts the bits from 1 to n in their binary form
for (int i = 30; i >= 0; i--) {
int power2 = 1 << i;
if(n/power2<1) // this two lines can be commented
continue; // can be commented
mask |= (n & power2);
int nRepeatOnes = n / (power2<<1) * power2 ;
int nLeftOnes = ( n>>i & 1) * (n - mask+1);
nBits += nRepeatOnes + nLeftOnes;
}
return nBits;
}
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
public class Solution {
public int maxProduct(int[] A) {
assert(A!=null && A.length >0);
if(A.length == 1)
return A[0];
int result = Integer.MIN_VALUE, maxEndHere = 1;// max positive product ending at the current position
int minEndHere = 1;// min negative product ending at the current position
for (int i = 0; i < A.length; i++) {
if (A[i] > 0) {
maxEndHere = maxEndHere * A[i];
minEndHere = Math.min(minEndHere * A[i],1);
result = Math.max(result,maxEndHere);
} else if(A[i]==0) {
maxEndHere = 1;
minEndHere = 1;
result = Math.max(result,0);// 0 can also be a product result
}else{ // A[i]<0
result = Math.max(minEndHere*A[i],result);
int tmp = maxEndHere;
maxEndHere = Math.max( minEndHere*A[i],1);
minEndHere = tmp*A[i];
}
}
return result;
}
}
Mistakes: