A: 对dfs和回溯的应用场景还是不太了解, 抬手一个回溯...wa了好几发 然后改成dfs过了
看了讲解, dfs可能会栈溢出,可以用状态压缩来避免
DFS写法:
long maxG =-1;
int VV=0;
int[] gg = null;
public int Maximumweight (int[] v, int[] g, int V) {
// write code here
VV= V;
gg=g;
dfs(v,0,0,0);
return (int)maxG;
}
public void dfs(int[] v, int pos,long cur,long weight){
if(cur > VV){
return;
}else if(cur == VV){
maxG = Math.max(maxG,weight);
return;
}
if(pos >=v.length){
return;
}
//不要
dfs(v,pos+1,cur,weight);
//要
dfs(v,pos+1,cur+v[pos],weight+gg[pos]);
} 状态压缩写法:
public int Maximumweight (int[] v, int[] g, int V) {
// write code here
int n = v.length;
int res =-1;
for(int i=0; i< 1<<n;++i){
int sumG =0;
int sumV=0;
int k=i;
int j=0;
while(k>0){
if((k&1)==1){
sumV += v[j];
sumG += g[j];
}
k = k>>1;
j++;
}
if(sumV ==V){
res = Math.max(res,sumG);
}
}
return res;
} B: kmp的next, 让字符串长度+1,返回next数组最后一位的值就行
public int solve (String s) {
int[] next = getNextArray((s+"#").toCharArray());
return next[next.length-1]==0 ? -1:next[next.length-1];
}
public static int[] getNextArray(char[] str){
if (str.length == 1) {
return new int[]{-1};
}
int[] next = new int[str.length];
next[0]=-1;
next[1]=0;
int cur=2;
int x=next[cur-1];
while(cur<str.length){
if(x==-1 || str[x] == str[cur-1] ){
next[cur++]=++x;
}else{
x=next[x];
}
}
return next;
} C: 我不配

京公网安备 11010502036488号