当前位置:网站首页>Daily question brushing record (III)
Daily question brushing record (III)
2022-06-25 08:14:00 【Unique Hami melon】
List of articles
The first question is : Brackets
LeetCode: Interview questions 08.09. Brackets
describe :
Brackets . Design an algorithm , Print n All legal for parentheses ( for example , One to one correspondence between opening and closing ) Combine .
explain : The solution set cannot contain duplicate subsets .
for example , give n = 3, The generated result is :
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
Their thinking :
Use backtracking here .
left Indicates the number of left parentheses . right Indicates the number of closing parentheses .
Build string , In case of disqualification, stop , Join if you meet the requirements list in
Pay attention to the pruning here ,
Code implementation :
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
backstrack(res,"",n,n);
return res;
}
public void backstrack(List<String> res,String str,int left,int right) {
// prune 1 left perhaps right Less than 0 The situation of
if(left < 0 || right < 0) return;
// prune 2 left > right The situation of
if(left > right) return;
// left and right All for 0 At this point, the conditions are met
if(left == 0 && right == 0) {
res.add(str);
return;
}
backstrack(res,str+"(",left-1,right);
backstrack(res,str+")",left,right-1);
}
}
The second question is : COINS
LeetCode: Interview questions 08.11. COINS
describe :
COINS . An unlimited number of coins , The value of the currency is 25 branch 、10 branch 、5 Points and 1 branch , Write code to calculate n There are several ways of expression .( The result could be big , You need to model the results 1000000007)
Their thinking :
Dynamic planning ideas :
- state F(i) : Indicates the current round up i The way
- State transition equation : F(i) = (F(i) + F(i-coin)) %1000000007
- The initial state : F(0) = 1; Because it can be drawn out with coins .
- Return results : F(n)
here coins = { 1, 5, 10, 25 };
If I just walk through it , There will be repetition , for example 5 + 10 and 10 + 5
Avoid this situation , You can use small loops , Using only one coin per small cycle can avoid repetition .
Code implementation :
class Solution {
public int waysToChange(int n) {
// Current coin situation
int[] coins = {
1,5,10,25};
int[] dp = new int[n+1];
// for example dp[1] = dp[1] + dp[0], This means that the current coin can be used , Initialization is 1
dp[0] = 1;
// The outer layer traverses this coins Array
for(int coin : coins) {
// Inner layer Traverse a coin
for(int i = coin;i <= n; i++) {
dp[i] = (dp[i] + dp[i-coin]) % 1000000007;
}
}
return dp[n];
}
}
Third question : Morpheme phrase
LeetCode: Interview questions 10.02. Morpheme phrase
describe :
Write a method , Sort the string array , Put all the morphemes together . Morphemes refer to the same letters , But arrange different strings .
Their thinking :
- Traverse , Let the traversed string be sorted , Add to HashMap in key Is the sorted string , value For one list
- The sorted characters are the same , Join in the same list in
- Add a new one if it is different list.
- After the traversal , Put all the list Add them together
Code implementation :
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> list = new ArrayList<>();
Map<String,List<String>> map = new HashMap<>();
for(String str : strs) {
// Sort
char[] ch = str.toCharArray();
Arrays.sort(ch);
// The sorted character array becomes a string
String s = new String(ch);
if(!map.containsKey(s)) {
// There is no such thing as the same key The situation of , You need to create a new list
List<String> ret = new ArrayList<>();
ret.add(str);
map.put(s,ret);
}else{
// There is the same key The situation of , Need to get the previous list, Then add data
map.get(s).add(str);
}
}
// Use keySet The way to get key, And then put all the value Values are added together .
for(String key : map.keySet()) {
list.add(map.get(key));
}
return list;
}
}
Fourth question : Minimum difference
LeetCode: Interview questions 16.06. Minimum difference
describe :
Given two arrays of integers a and b, Calculate a pair of values with the absolute value of the minimum difference ( Take one value from each array ), And return the difference of the logarithm 
Their thinking :
- Define two pointers , left right, Sort two arrays .
- use ret Record the current a[left] - b[right] The difference between the
If ret > 0, a[left]>b[right], let right++, In order to make b It's closer a Value
If ret < 0, a[left]<b[right], let left++, In order to make a It's closer b Value
Record The smallest ret
Code implementation :
class Solution {
public int smallestDifference(int[] a, int[] b) {
// Prioritize
Arrays.sort(a);
Arrays.sort(b);
// Notice the overflow here
long min = Integer.MAX_VALUE;
int left = 0;
int right = 0;
while(left < a.length && right < b.length) {
// long Prevent overflow
long ret = a[left] - b[right];
// Record minimum
min = Math.min(Math.abs(ret),min);
// Subtract the closer values
if(ret < 0) left++;
else right++;
}
return (int)min;
}
}
Fifth question : The first common ancestor
LeetCode: Interview questions 04.08. The first common ancestor
describe :
Design and implement an algorithm , Find the first common ancestor of two nodes in the binary tree . Do not store other nodes in another data structure . Be careful : This is not necessarily a binary search tree .
for example , Given the following binary tree : root = [3,5,1,6,2,0,8,null,null,7,4]

Their thinking :
- Possible situations :
①p and q There is a root node , Then the root node is the nearest common ancestor
②p and q Not under the same subtree , Then their father is the common ancestor
③p and q Under the same subtree- Recursive left and right subtrees
① Left and right subtrees are not empty , that root Is the common ancestor
② The left subtree is empty , The right subtree is not empty , Then the node found in the right tree is the common ancestor
③ The left subtree is not empty , The right subtree is empty , Then the node found in the left tree is the common ancestor
Code implementation :
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// Situation 1 : The root node is empty
if (root == null) return null;
// Situation two : p or q Root node
if (p == root || q == root) return root;
// Traverse the left and right subtrees
TreeNode leftNode = lowestCommonAncestor(root.left,p,q);
TreeNode rightNode = lowestCommonAncestor(root.right,p,q);
// It's not empty. , that root Is the common ancestor
if(leftNode != null && rightNode != null) {
return root;
}
// The left subtree is empty , The node of the right tree is the common ancestor
if(leftNode == null){
return rightNode;
}
// The right subtree is empty , The node of the left tree is the common ancestor
if(rightNode == null) {
return leftNode;
}
return null;
}
}
Sixth question : Minimum height tree
LeetCode: Interview questions 04.02. Minimum height tree
describe :
Given an ordered array of integers , The elements are different and in ascending order , Write an algorithm , Create a minimum height binary search tree .
Their thinking :
- Here we use the dichotomy method to segment , Every time you get a middle point , Then construct a node .
- Then take a middle point on the left , Construct the left node , And then on the right, get a middle point , Construct the right node .
Code implementation :
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return makeBST(nums,0,nums.length-1);
}
public TreeNode makeBST(int[] nums, int left, int right) {
// If left>right It's not legal
if (left > right) {
return null;
}
// Prevent overflow here , Use left+(right-left)/2
int mid = left + (right - left) / 2;
// Construct a node
TreeNode node = new TreeNode(nums[mid]);
// Constructing left and right subtrees
node.left = makeBST(nums, left, mid - 1);
node.right = makeBST(nums, mid+1, right);
return node;
}
}
边栏推荐
- TCP stuff
- Startup, shutdown and restart of Oracle and MySQL on Linux
- FFT [template]
- Matlab代码格式一键美化神器
- [supplementary question] 2021 Niuke summer multi school training camp 9-N
- Matlab code format one click beautification artifact
- 电子学:第009课——实验 7:研究继电器
- Use the frame statistics function of the message and waveform recording analyzer royalscope to troubleshoot the accidental faults of the CAN bus
- 每日刷题记录 (三)
- 洛谷P1073 [NOIP2009 提高组] 最优贸易(分层图+最短路)
猜你喜欢

What is SKU and SPU? What is the difference between SKU and SPU

网络模型——OSI模型与TCP/IP模型

CVPR 2022 oral 2D images become realistic 3D objects in seconds

Electronics: Lesson 008 - Experiment 6: very simple switches

Socket problem record

allgero报错:Program has encountered a problem and must exit. The design will be saved as a .SAV file

静态网页服务器

初体验完全托管型图数据库 Amazon Neptune

Can bus working condition and signal quality "physical examination"

Three Siemens fire-fighting hosts fc18 are equipped with can optical transceiver for optical fiber redundant ring network networking test
随机推荐
洛谷P6822 [PA2012]Tax(最短路+边变点)
测一测现在的温度
Neural network and deep learning-3-simple example of machine learning pytorch
How do I install the software using the apt get command?
Electronics: Lesson 012 - Experiment 11: light and sound
函数尽量不要通过变量指定操作类型
Self made ramp, but it really smells good
c#ColorDialog更改文本颜色和FontDialog更改文本字体的使用示例
Luogu p5994 [pa2014]kuglarz (XOR thinking +mst)
Solving some interesting problems with recurrence of function
Opencv minimum filtering (not limited to images)
初体验完全托管型图数据库 Amazon Neptune
Force buckle 272 Closest binary search tree value II recursion
图像超分综述:超长文一网打尽图像超分的前世今生 (附核心代码)
深度学习系列48:DeepFaker
Startup, shutdown and restart of Oracle and MySQL on Linux
【补题】2021牛客暑期多校训练营4-n
c#中设置lable控件的TextAlign属性控制文字居中的方法
电子学:第008课——实验 6:非常简单的开关
Can transparent cloud gateway caniot and candtu record can messages and send and receive can data remotely

