Skip to content

Commit 0336fed

Browse files
增加题784字母大小写全排列1解,更新NOTE内容
1 parent 02040a6 commit 0336fed

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

Week_04/id_18/LeetCode_784_18.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,31 @@ private void dfs(StringBuilder sb, int index) {
3030
dfs(sb, index + 1);
3131
}
3232
}
33+
34+
public List<String> letterCasePermutation1(String S) {
35+
dfs(S.toCharArray(), 0);
36+
return list;
37+
}
38+
39+
private void dfs(char[] cs, int index) {
40+
if (index == cs.length) {
41+
list.add(new String(cs));
42+
return;
43+
}
44+
45+
if (cs[index] < 'A') {
46+
dfs(cs, index + 1);
47+
} else {
48+
char c = cs[index];
49+
if (c > 64 && c < 91) {
50+
dfs(cs, index + 1);
51+
cs[index] = (char) (cs[index] + 'a' - 'A');
52+
dfs(cs, index + 1);
53+
} else {
54+
dfs(cs, index + 1);
55+
cs[index] = (char) (cs[index] + 'A' - 'a');
56+
dfs(cs, index + 1);
57+
}
58+
}
59+
}
3360
}

Week_04/id_18/NOTE.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,5 +404,40 @@ class Solution {
404404
}
405405
}
406406
```
407+
#### 优化代码
408+
参考了国内站的另一种回溯解法,其中讨论了为什么在步骤类似的情况下,这种算法的时间会更短,他的结论是在做判断字符是否为数字的动作时,直接使用ASCII码进行比较比**Character.isDigit**方法更快。
409+
410+
我也进行了尝试。而我的另一个不同是,我使用的是StringBuilder对象,而其使用的是字符数组。在使用优化的方法后,代码的执行时间果然减少了,同时空间占用的大小也减小了,原因应该是StringBuilder类型的对象中还维护了一些题目中不需要的属性。
411+
```java
412+
class Solution {
413+
List<String> list = new ArrayList<>();
414+
public List<String> letterCasePermutation(String S) {
415+
dfs(S.toCharArray(), 0);
416+
return list;
417+
}
418+
419+
private void dfs(char[] cs, int index) {
420+
if (index == cs.length) {
421+
list.add(new String(cs));
422+
return;
423+
}
424+
425+
if (cs[index] < 'A') {
426+
dfs(cs, index + 1);
427+
} else {
428+
char c = cs[index];
429+
if (c > 64 && c < 91) {
430+
dfs(cs, index + 1);
431+
cs[index] = (char) (cs[index] + 'a' - 'A');
432+
dfs(cs, index + 1);
433+
} else {
434+
dfs(cs, index + 1);
435+
cs[index] = (char) (cs[index] + 'A' - 'a');
436+
dfs(cs, index + 1);
437+
}
438+
}
439+
}
440+
}
441+
```
407442
### 收获
408443
熟悉和练习了回溯算法

0 commit comments

Comments
 (0)