ARTS - 2020.10.05 ~ 2020.10.11

ARTS打卡 - 15

1. Algorithm

22. Generate Parentheses

题目大意是括号生成,给定一个数字,例如 n = 3 ,表示一共有三个括号对:”()”,输出所有可能的括号组合:["((()))","(()())","(())()","()(())","()()()"]

首先想由于要组成有效括号,左括号的数量要始终小于右括号的数量,才有可能组成有效括号,所以应该先把左括号全部排列,之后再排列右括号。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
List<String> results = new ArrayList<>();
public List<String> generateParenthesis(int n) {
recursionParenthesis("", n, n);
return results;
}

public void recursionParenthesis(String res, int left, int right) {
if(left == 0 && right == 0) {
results.add(res);
return;
}
if(left > 0)
recursionParenthesis(res+"(", left-1, right);
if(right > left)
recursionParenthesis(res+")", left, right-1);
}
}

如上述代码所示,首先递归将所有左括号拼接,再递归拼接右括号。

2. Review

Kotlin Coroutines in Android: Understanding suspend functions and main-safety by example

  1. 一个函数,加了suspend,一定是运行在后台线程的吗?

如果没有特殊说明,那么suspend函数将会运行在主线程而不是后台线程。

  • 一个suspend函数将会被协程调用

  • 如果需要执行很长的任务,它将会在调用线程挂起, 而调用线程继续执行

  • 当suspend协程挂起时,其余在调用线程上的函数依然可以运行

  • 当suspend 阻塞函数的结果返回后,该协程继续运行。

  1. 自从ViewModelScope将Dispatcher.Main作为dispatcher之后,viewModelScope.launch自动运行在主线程。

  2. 需要选择正确的dispatcher来决定suspend 函数是否会阻塞主线程,IO密集型选择Dispatcher.IO, CPU密集型选择Dispatcher.Default

3. Tip

很久没有遇到过依赖冲突的问题了,基本上不引入新库就不会遇到,这次遇到了一个依赖冲突的问题,刚好重新徐学习下:可以运行: ./gradlew -q :app:appDependencies [--configuration] [implementation] 查看依赖树,一般会提示哪个module下的哪个依赖冲突,这时可以先注释掉其中一个,然后查看剩下的依赖是在哪里,最后使用exclude去除这个依赖:

1
2
3
implementation (project(':base-network'),{
exclude group:'com.squareup.okhttp3'
})

4. Share

美团外卖客户端容器化架构的演进