LC96. 不同的二叉搜索树
//卡特兰公式
class Solution {
public int numTrees(int n) {
int[] dp = new int[n+1];
dp[0] = 1;
dp[1] = 1;
for(int i = 2; i < n + 1; i++)
for(int j = 1; j < i + 1; j++)
dp[i] += dp[j-1] * dp[i-j];
return dp[n];
}
}
// G(n) = G(0)*G(n - 1) + G(1)*G(n-2) + ....G(n - 1)*G(0)
卡特兰公式
LC547. 省份数量
//二维数组的dfs,主函数控制行,内层循环控制列。注意题目需要几个参数
class Solution {
public int findCircleNum(int[][] isConnected) {
int provinces = isConnected.length;
boolean[] visited = new boolean[provinces];
int circles = 0;
//外层控制行[0][1][2]
for(int i = 0;i < provinces;i++){
if(!visited[i]){
dfs(isConnected,visited,provinces,i);
circles++;
}
}
return circles;
}
public void dfs(int[][] isConnected,boolean[] visited,int provinces,int i){
for(int j = 0;j < provinces;j++){
if(isConnected[i][j] == 1 && !visited[j]){
visited[j] = true;
//这里内层变量要发生变化
//内层就是[0,0][0,1][0,2]这样
dfs(isConnected,visited,provinces,j);
}
}
}
}
LC264. 丑数 II
//求第几个数字,可以考虑说用小根堆,并且根据题意得我们可以将2x,3x,5x得数字一个个放入到堆当中,最后弹出堆顶即可。
class Solution {
public int nthUglyNumber(int n) {
int[] factors = new int[]{2,3,5};
PriorityQueue<Long> heap = new PriorityQueue();
Set<Long> seen = new HashSet();
seen.add(1L);
heap.offer(1L);
int ugly = 0;
for(int i = 0;i < n;i++){
long cur = heap.poll();
ugly = (int) cur;
for(int factor : factors){
long next = cur*factor;
if(seen.add(next)){
heap.offer(next);
}
}
}
return ugly;
}
}