classSolution{public:intlongestPalindromeSubseq(string s){int n = s.size();
vector<vector<int>>f(n, vector<int>(n));for(int len =1; len <= n; len ++)for(int i =0; i + len -1< n; i ++){int j = i + len -1;if(len ==1) f[i][j]=1;else{if(s[i]== s[j]) f[i][j]= f[i +1][j -1]+2;
f[i][j]=max(f[i][j],max(f[i +1][j], f[i][j -1]));}}return f[0][n -1];}};
classSolution{publicintlongestPalindromeSubseq(String s){int n = s.length();// 状态表示数组,两个维度分别表示区间的左右端点,数值表示区间最大回文长度int[][] f =newint[n][n];int res =0;// 先枚举区间长度for(int len =1; len <= n; len ++){// 再枚举区间左右端点for(int i =0; i + len -1< n; i++){int j = i + len -1;// 特判长度为1的情况if(len ==1) f[i][j]=1;else{// 不用当前两个端点为回文边界的情况
f[i][j]= Math.max(f[i +1][j], f[i][j -1]);// 如果两个当前区间的两个端点相同,那就用if(s.charAt(i)== s.charAt(j)){
f[i][j]= f[i +1][j -1]+2;}}// 取最大值
res = Math.max(f[i][j], res);}}return res;}}
classSolution:deflongestPalindromeSubseq(self, s:str)->int:
n =len(s)
dp =[[0for _ inrange(n)]for _ inrange(n)]for i inrange(n):
dp[i][i]=1for i inrange(n-1,-1,-1):#遍历顺序由dp关系式所得for j inrange(i+1, n):if s[i]== s[j]:
dp[i][j]= dp[i+1][j-1]+2else:
dp[i][j]=max(dp[i+1][j], dp[i][j-1])return dp[0][n-1]#dp处理两个端点
funclongestPalindromeSubseq(s string)int{var n =len(s)var dp =make([][]int, n)for i :=0; i < n; i++{
dp[i]=make([]int, n)
dp[i][i]=1}//for i := 0; i < n; i++ {// fmt.Println(dp[i])//}for i := n-1; i >=0; i--{for j := i +1; j < n; j++{if s[i]== s[j]{
dp[i][j]= dp[i+1][j-1]+2}else{
dp[i][j]=max(dp[i+1][j], dp[i][j-1])}}}//for i := 0; i < n; i++ {// fmt.Println(dp[i])//}return dp[0][n-1]}funcmax(i1 int, i2 int)int{if i1 > i2 {return i1
}return i2
}
第五百一十七题:
classSolution{public:intfindMinMoves(vector<int>& w){int sum =0, n = w.size();for(auto x: w) sum += x;if(sum % n)return-1;int avg = sum / n, left =0, right = sum;int res =0;for(int i =0; i < n; i ++){
right -= w[i];if(i) left += w[i -1];int l =max(avg * i - left,0);int r =max(avg *(n - i -1)- right,0);
res =max(res, l + r);}return res;}};
classSolution{publicintfindMinMoves(int[] machines){int n = machines.length, dressTotal =0;for(int m : machines) dressTotal += m;if(dressTotal % n !=0)return-1;int dressPerMachine = dressTotal / n;// Change the number of dresses in the machines to// the number of dresses to be removed from this machine// (could be negative)for(int i =0; i < n; i++) machines[i]-= dressPerMachine;// currSum is a number of dresses to move at this point, // maxSum is a max number of dresses to move at this point or before,// m is number of dresses to move out from the current machine.int currSum =0, maxSum =0, tmpRes =0, res =0;for(int m : machines){
currSum += m;
maxSum = Math.max(maxSum, Math.abs(currSum));
tmpRes = Math.max(maxSum, m);
res = Math.max(res, tmpRes);}return res;}}
classSolution:deffindMinMoves(self, machines: List[int])->int:
n =len(machines)
dress_total =sum(machines)if dress_total % n !=0:return-1
dress_per_machine = dress_total // n
for i inrange(n):# Change the number of dresses in the machines to# the number of dresses to be removed from this machine# (could be negative)
machines[i]-= dress_per_machine
# curr_sum is a number of dresses to move at this point, # max_sum is a max number of dresses to move at this point or before,# m is number of dresses to move out from the current machine.
curr_sum = max_sum = res =0for m in machines:
curr_sum += m
max_sum =max(max_sum,abs(curr_sum))
res =max(res, max_sum, m)return res
funcabs(a int)int{if a<0{return-a
}return a
}funcfindMinMoves(machines []int)int{
sum :=0for_, machine :=range machines {
sum +=machine
}if sum %len(machines)!=0{return-1}
avg := sum /len(machines)var ans =math.MinInt32
for i, machine :=range machines {
machines[i]= machine-avg
}for i:=0;i<len(machines)-1;i++{if ans <abs(machines[i]){
ans =abs(machines[i])}if ans < machines[i+1]{
ans = machines[i+1]}
machines[i+1]+=machines[i]}if ans < machines[len(machines)-1]{return machines[len(machines)-1]}return ans
}
第五百一十八题:
classSolution{public:intchange(int amount, vector<int>& coins){
vector<int>f(amount +1);
f[0]=1;for(auto x: coins)for(int i = x; i <= amount; i ++)
f[i]+= f[i - x];return f[amount];}};
classSolution:defchange(self, amount:int, coins: List[int])->int:
dp =[0]*(amount +1)
dp[0]=1for coin in coins:for x inrange(coin, amount +1):
dp[x]+= dp[x - coin]return dp[amount]
//由于dp[i]只和dp[i-1]有关,可以进行状态压缩funcchange2(amount int, coins []int)int{
n :=len(coins)
dp :=make([]int, amount+1)
dp[0]=1for i :=1; i <= n; i++{for j :=1; j <= amount; j++{if j-coins[i-1]>=0{
dp[j]= dp[j]+ dp[j-coins[i-1]]}}}return dp[amount]}
第五百一十九题:
classSolution{public:int r, c, k;
unordered_map<int,int> hash;Solution(int n_rows,int n_cols){
r = n_rows, c = n_cols;
k = r * c;}
vector<int>flip(){int x =rand()% k;int y = x;if(hash.count(x)) y = hash[x];if(hash.count(k -1)){
hash[x]= hash[k -1];
hash.erase(k -1);}else{
hash[x]= k -1;}
k --;return{y / c, y % c};}voidreset(){
k = r * c;
hash.clear();}};/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(n_rows, n_cols);
* vector<int> param_1 = obj->flip();
* obj->reset();
*/
classSolution{int nr, nc, rem, b_size;
List<Set<Integer>> buckets =newArrayList<>();
Random rand =newRandom();publicSolution(int n_rows,int n_cols){
nr = n_rows;
nc = n_cols;
rem = nr * nc;
b_size =(int) Math.sqrt(nr * nc);for(int i =0; i < nr * nc; i+= b_size)
buckets.add(newHashSet<Integer>());}publicint[]flip(){int c =0;int c0 =0;int k = rand.nextInt(rem);for(Set<Integer> b1 : buckets){if(c0 + b_size - b1.size()> k){while(true){if(!b1.contains(c)){if(c0 == k){
b1.add(c);
rem--;returnnewint[]{c / nc, c % nc};}
c0++;}
c++;}}
c += b_size;
c0 += b_size - b1.size();}return null;}publicvoidreset(){for(Set<Integer> b1 : buckets)
b1.clear();
rem = nr * nc;}}
type Solution struct{
Cols int
TotalCnt int
Total1Cnt int
Flipped map[int]int// Key:FlippedIndex Value:RepalceIndex}funcConstructor(n_rows int, n_cols int) Solution {return Solution{
Cols: n_cols,
TotalCnt: n_rows * n_cols,
Total1Cnt:0,
Flipped:map[int]int{},}}func(this *Solution)Flip()[]int{
randP := rand.Intn(this.TotalCnt - this.Total1Cnt)
x := randP
this.Total1Cnt++if_, has := this.Flipped[x]; has {
x = this.Flipped[x]}if v, has := this.Flipped[this.TotalCnt-this.Total1Cnt]; has {
this.Flipped[randP]= v
}else{
this.Flipped[randP]= this.TotalCnt - this.Total1Cnt
}return[]int{x/this.Cols, x%this.Cols}}func(this *Solution)Reset(){
this.Total1Cnt =0
this.Flipped =map[int]int{}}/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(n_rows, n_cols);
* param_1 := obj.Flip();
* obj.Reset();
*/
第五百二十题:
classSolution{public:boolcheck(char c){return c >='A'&& c <='Z';}booldetectCapitalUse(string word){int s =0;for(auto c: word)if(check(c))
s ++;return s == word.size()||!s || s ==1&&check(word[0]);}};
funcdetectCapitalUse(word string)bool{return word == strings.ToUpper(word)|| word == strings.ToLower(word)|| word == strings.Title(strings.ToLower(word))}
第五百二十一题:
classSolution{public:intfindLUSlength(string a, string b){if(a == b)return-1;returnmax(a.size(), b.size());}};
publicclassSolution{publicintfindLUSlength(String a, String b){if(a.equals(b))return-1;return Math.max(a.length(), b.length());}}
funcfindLUSlength(a string, b string)int{if a == b {return-1}returnlen(maxString(a, b))}funcmaxString(a, b string)string{iflen(a)>len(b){return a
}else{return b
}}
第五百二十二题:
classSolution{public:boolcheck(string& a, string& b){int k =0;for(auto c: b)if(k < a.size()&& c == a[k])
k ++;return k == a.size();}intfindLUSlength(vector<string>& strs){int res =-1;for(int i =0; i < strs.size(); i ++){bool is_sub =false;for(int j =0; j < strs.size(); j ++)if(i != j &&check(strs[i], strs[j])){
is_sub =true;break;}if(!is_sub) res =max(res,(int)strs[i].size());}return res;}};
publicclassSolution{publicbooleanisSubsequence(String x, String y){int j =0;for(int i =0; i < y.length()&& j < x.length(); i++)if(x.charAt(j)== y.charAt(i))
j++;return j == x.length();}publicintfindLUSlength(String[] strs){
Arrays.sort(strs,newComparator< String >(){publicintcompare(String s1, String s2){return s2.length()- s1.length();}});for(int i =0, j; i < strs.length; i++){boolean flag =true;for(j =0; j < strs.length; j++){if(i == j)continue;if(isSubsequence(strs[i], strs[j])){
flag =false;break;}}if(flag)return strs[i].length();}return-1;}}
classSolution:deffindLUSlength(self, strs: List[str])->int:# 判读s1是否是s2的子序列defcheck(s1, s2):iflen(s1)>len(s2):returnFalseif s1 == s2:returnTrue
i, loc =0,-1while i <len(s1)and(loc := s2.find(s1[i], loc +1))!=-1:
i +=1return i ==len(s1)# 按长度从长到短排序
strs.sort(key=len, reverse=True)for idx1, s1 inenumerate(strs):# 看s1是否全不是其他字符串的子序列的ifall(not check(s1, s2)for idx2, s2 inenumerate(strs)if idx1 != idx2):returnlen(s1)return-1
第五百一十六题:class Solution {public: int longestPalindromeSubseq(string s) { int n = s.size(); vector<vector<int>> f(n, vector<int>(n)); for (int len = 1; len <= n; len ++ ) for (int i = 0; i + len