目录
拼写单词
class Solution {
public int countCharacters(String[] words, String chars) {
int[] chars_count = count(chars); // 统计字母表的字母出现次数
int res = 0;
for (String word : words) {
int[] word_count = count(word); // 统计单词的字母出现次数
if (contains(chars_count, word_count)) {
res += word.length();
}
}
return res;
}
// 检查字母表的字母出现次数是否覆盖单词的字母出现次数
boolean contains(int[] chars_count, int[] word_count) {
for (int i = 0; i < 26; i++) {
if (chars_count[i] < word_count[i]) {
return false;
}
}
return true;
}
// 统计 26 个字母出现的次数
int[] count(String word) {
int[] counter = new int[26];
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
counter[c-'a']++;
}
return counter;
}
}
李白打酒(递归)
package 往年例题;
/**
* @author diao 2022/3/21
*/
public class 李白打酒 {
//因为一共有15个地方
static char[] c=new char[16];
static int sum=0;
public static void main(String[] args) {
c[15]='\0';
fun(2,1,0,0);
}
/**
* 店的个数>15,斗里没有酒就结束n<0
* 斗中酒为0,店也走满 结束
* @param now:斗中酒总个数
* @param n:当前走的第几个店或者花
* @param d 总店数
* @param h 总花数
*/
public static void fun(int now,int n,int d,int h){
// 1.结束条件
if(now<0||n>16||(now==0&&n<16)){
return;
}
if(now==0){
if(n==16&&d==5&&h==10){
sum++;
System.out.print("sum:"+sum+" ");
/*输出字符数组*/
System.out.println(c);
}
}
// 2.递归逻辑
/*第一种情况:假设走店 */
c[n-1]='a';
fun(now*2,n+1,d+1,h);
/*第二种情况:假设走花*/
c[n-1]='b';
fun(now-1,n+1,d,h+1);
}
}
大数阶乘(利用BigInteger与Long)
package 往年例题.省赛模拟题;
import java.math.BigInteger;
import java.util.Scanner;
/**
* @author diao 2022/3/21
*/
public class 大数阶乘2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//1.输入阶乘数
long num = sc.nextLong();
BigInteger res = new BigInteger("1");
while(num>0){
res=res.multiply(BigInteger.valueOf(num));
//将阶乘数不断缩小,当为0时结束
num-=1;
}
System.out.println(res);
sc.close();
}
}
利用递归普通阶乘
package 往年例题.省赛模拟题;
/**
* @author diao 2022/3/21
*/
public class 大数阶乘 {
public static void main(String[] args) {
int dfs = dfs(4);
System.out.println(dfs);
}
public static int dfs(int n){
//1.结束条件,也就是开始归的条件
if(n==1){
return 1;
}
//2.递归思路:当前数的递归=之前的数递归+当前数
return dfs(n-1)*n;
}
}