고유한 하위 시퀀스 Leetcode
7171 단어 javadpalgorithms
문자열의 하위 시퀀스는 나머지 문자의 상대 위치를 방해하지 않고 문자 중 일부(없을 수 있음)를 삭제하여 원래 문자열에서 형성된 새 문자열입니다. (즉, "ACE"는 "ABCDE"의 하위 시퀀스이고 "AEC"는 그렇지 않습니다).
답이 부호 있는 32비트 정수에 맞도록 테스트 케이스가 생성됩니다.
예 1:
Input: s = "rabbbit", t = "rabbit"
Output: 3
설명:
As shown below, there are 3 ways you can generate "rabbit" from S.
rabbbit
rabbbit
rabbbit
class Solution {
public int numDistinct(String s, String t) {
// we will use little bit of backtracking here
int dp[][] = new int[s.length()][t.length()];
for(int row[] : dp) Arrays.fill(row, -1);
return distinctCount(s,t,s.length()-1,t.length()-1,dp);
}
public int distinctCount(String s, String t, int i,int j,int dp[][]){
//base case
if(i=0 && j=0 && s.charAt(i)==t.charAt(j)) return 1;
if(j<0) return 1;
if(i<0) return 0;
if(dp[i][j]!=-1) return dp[i][j];
if(s.charAt(i)==t.charAt(j)){
// so basically if its a, match , we will either reduce s and t index both or we will just reduce the index of s only.
// in both the case we will return the sum of values that we get.
return dp[i][j]= distinctCount(s,t,i-1,j-1,dp) + distinctCount(s,t,i-1,j,dp);
}
else{
// else if its not a match we will have to reduce the s string index so
//as to reach to an index of s where s.charAt(i) == t.charAt(j);
return dp[i][j] = distinctCount(s,t,i-1,j,dp);
}
}
}
Reference
이 문제에 관하여(고유한 하위 시퀀스 Leetcode), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/prashantrmishra/distinct-subsequence-leetcode-4e9l텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)