数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例 1:

1
2
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

1
2
输入:n = 1
输出:["()"]

题解:暴力递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public List<String> generateParenthesis(int n) {
List<String> combinations = new ArrayList<String>();
generateAll(new char[2*n], 0, combinations);
return combinations;
}
public void generateAll(char[] current, int pos, List<String> result) {
if(pos == current.length) {
if (valid(current)) {
result.add(new String(current));
}
} else {
current[pos]='(';
generateAll(current, pos+1, result);
current[pos]=')';
generateAll(current, pos+1, result);
}
}

public boolean valid(char[] current) {
int balance = 0;
for (char c : current ) {
if(c == '(') {
balance++;
} else {
balance--;
}
if (balance < 0) {
return false;
}
}
return balance == 0;
}
}

169. 多数元素

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

1
2
输入:[3,2,3]
输出:3

示例 2:

1
2
输入:[2,2,1,1,1,2,2]
输出:2

解法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
// 计算每个数出现的次数
private Map<Integer, Integer> countNums(int[] nums) {
Map<Integer,Integer> counts = new HashMap<Integer, Integer>();
for(int num:nums) {
if(!counts.containsKey(num)) counts.put(num,1);
else counts.put(num, counts.get(num)+1);
}
return counts;
}
// 打擂台选出最大数
public int majorityElement(int[] nums) {
Map<Integer,Integer> counts = countNums(nums);
Map.Entry<Integer, Integer> majorityEntry = null;
for(Map.Entry<Integer, Integer> entry : counts.entrySet()) {
if(majorityEntry == null || entry.getValue() > majorityEntry.getValue()) majorityEntry = entry;
}
return majorityEntry.getKey();

}
}