Beginner algorithm brush Day4
Keywords:
Algorithm
Dynamic Programming
- Maximum Square: the idea is to solve it by dynamic programming. Traverse all possible lengths, regard each point in the matrix as the lower right corner of the square under this length, and judge whether there is a square with this point as the lower right corner under the current length. DP[i][j] is equal to the area. The judgment condition is to determine that the upper, left and upper left values of this point are not less than the length * length of the previous round. Add an ans and update the ans every time a larger area is found. Finally, the answer is to return ans.
-
class Solution {
public int maximalSquare(char[][] matrix) {
int maxLength = matrix.length > matrix[0].length ? matrix[0].length : matrix.length;
int[][] DP = new int[matrix.length][matrix[0].length];
int ans = 0;
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(matrix[i][j] == '0'){
DP[i][j] = 0;
}else{
DP[i][j] = 1;
ans = 1;
}
}
}
for(int length = 2; length <= maxLength; length++){
int lastArea = (length - 1) * (length - 1);
for(int i = length - 1; i < matrix.length; i++){
for(int j = length - 1; j < matrix[0].length; j++){
if(DP[i - 1][j] >= lastArea && DP[i][j - 1] >= lastArea && DP[i - 1][j - 1] >= lastArea && DP[i][j] > 0){
DP[i][j] = length*length;
ans = DP[i][j] > ans ? DP[i][j] : ans;
}
}
}
}
return ans;
}
}
- String decoding: traverse the string, turn all characters into strings before ']' and put them on the stack in turn ']' After that, start the stack until you encounter '[ ', Add up the characters just out of the stack. (for the string, the result of s1 + s2 is different from that of s2 + s1), and pop up another one, because the current top of the stack is' [', continue to stack until the top element of the stack is not a number of 0 - 9 or the stack is empty. Find the number of times this block needs to be repeated. It is also added through the top element of the stack. Because it is a string class, you need to pay attention to the order. After generating a new string, press it into the stack and continue to go down. Get the result
-
class Solution {
public String decodeString(String s) {
Stack<String> stack = new Stack<String>();
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(ch == ']'){
String str = "";
while(!stack.peek().equals("[")){
str = stack.pop() + str;
}
stack.pop();
String repeatString = "";
while(!stack.isEmpty() && (stack.peek().charAt(0) >= '0' && stack.peek().charAt(0) <= '9')){
repeatString = stack.pop()+ repeatString;
}
int repeatTimes = Integer.parseInt(repeatString);
String partAns = "";
for(int j = 0; j < repeatTimes; j++){
partAns = partAns + str;
}
stack.push(partAns);
}else{
stack.push(ch + "");
}
}
String ans = "";
while(!stack.isEmpty()){
ans = stack.pop() + ans;
}
return ans;
}
}
- Rabbits in the forest: sort the rabbit's answers into Arrays.sort(answers); (don't remember the method name wrong again) Traversing the array, 0 means that there is at least one such rabbit, so all zeros add 1 to the final answer. Then look back to find how many numbers are the same as the current position. These rabbits with the same answer can be regarded as a class, but the number of the same number cannot operate the current number + 1. Look back until there is no rabbit. Note that if the last rabbit does not If you belong to any kind of answer, you also need to add the answer of the last sub rabbit + 1;
-
class Solution {
public int numRabbits(int[] answers) {
Arrays.sort(answers);
int sameRabit = 0;
int ans = 0;
for(int i = 0; i < answers.length; i++){
for(int j = i + 1; j < answers.length; j++){
if(answers[j] == answers[i] && answers[j] != 0 && sameRabit < answers[i]){
sameRabit++;
}else{
ans += answers[i] + 1;
i += sameRabit;
sameRabit = 0;
break;
}
}
if(i == answers.length - 1){
ans += answers[i] + 1;
}
}
return ans;
}
}
- Sum of three numbers: give an array containing n integers, judge whether the sum of three numbers is equal to 0, and find all non repeating triples with a sum of 1. First arrange the array, Arrays.sort(arr) ; using the idea of Full Permutation, find out all combinations to judge whether they are appropriate or not. It is not exactly the same as full permutation, because the combination of the same three numbers in different positions has no meaning, so we don't need an array to mark whether a number has been accessed. We just need to let the program find the next number from the current position. Finally, it exceeded the time limit and thought for a few minutes There are two ways to limit the generation of useless combinations. The first is that when the selected first and second numbers plus the number of the tail of the array are still less than 0, there is no need to recurse down. The second is that when the selected first number is still smaller than the sum of the two tail numbers and 0, there is no need to recurse down. This optimization still exceeds the time limit. We will improve it later. Store the results here The data structure of is HashSet. Because it is a sorted array, if (1, 1, - 2) and (- 2, 1, 1) do not occur when generating addable results, we only need to consider the case that there are three consecutive ones in the array.
- The Java HashSet traversal can use the enhanced for loop (for (type) item: set)..
-
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ansReal = new ArrayList<List<Integer>>();
List<Integer> possibleAns = new ArrayList<Integer>();
HashSet<List<Integer>> ans = new HashSet<List<Integer>>();
Arrays.sort(nums);
backTrack(ans, possibleAns, 0, nums, 0);
for(List item : ans){
ansReal.add(item);
}
return ansReal;
}
public void backTrack(HashSet<List<Integer>> ans, List<Integer> possibleAns, int curStep, int[] numsReal, int starPos){
if(curStep == 3){
int sum = 0;
for(int i = 0; i < possibleAns.size(); i++){
sum += possibleAns.get(i);
}
if(sum == 0 && possibleAns.size() == 3){
ans.add(new ArrayList<Integer>(possibleAns));
}
return;
}else{
for(int i = starPos; i < numsReal.length; i++){
possibleAns.add(numsReal[i]);
if(possibleAns.size() == 1 && numsReal.length > 2){
if(possibleAns.get(0) + numsReal[numsReal.length - 2] + numsReal[numsReal.length - 1] < 0){
possibleAns.remove(possibleAns.size() - 1);
continue;
}
}
if(possibleAns.size() == 2){
if(possibleAns.get(0) + possibleAns.get(1) + numsReal[numsReal.length - 1] < 0){
possibleAns.remove(possibleAns.size() - 1);
continue;
}
}
backTrack(ans, possibleAns, curStep + 1, numsReal, i + 1);
possibleAns.remove(possibleAns.size() - 1);
}
}
}
}
Posted by knucklehead on Fri, 17 Sep 2021 07:55:34 -0700