File tree Expand file tree Collapse file tree 5 files changed +77
-0
lines changed Expand file tree Collapse file tree 5 files changed +77
-0
lines changed Original file line number Diff line number Diff line change 1+ function combinationSum ( candidates : number [ ] , target : number ) : number [ ] [ ] {
2+ const results : number [ ] [ ] = [ ] ;
3+
4+ function backtrack ( currentIndex : number , sum : number , selected : number [ ] ) {
5+ if ( sum > target ) return ;
6+ if ( sum === target ) {
7+ results . push ( [ ...selected ] ) ;
8+ return ;
9+ }
10+
11+ for ( let i = currentIndex ; i < candidates . length ; i ++ ) {
12+ selected . push ( candidates [ i ] ) ;
13+ backtrack ( i , sum + candidates [ i ] , selected ) ;
14+ selected . pop ( ) ;
15+ }
16+ }
17+
18+ backtrack ( 0 , 0 , [ ] ) ;
19+
20+ return results ;
21+ }
Original file line number Diff line number Diff line change 1+ function numDecodings ( s : string ) : number {
2+ const sLen = s . length ;
3+ const isValid = ( s : string ) : boolean => {
4+ if ( s [ 0 ] === "0" ) return false ;
5+
6+ return Number ( s ) > 0 && Number ( s ) <= 26 ;
7+ } ;
8+
9+ if ( sLen === 0 ) return 0 ;
10+ if ( s . length === 1 ) return isValid ( s [ 0 ] ) ? 1 : 0 ;
11+
12+ // dp[i]: i번째 위치까지 디코딩할 수 있는 방법의 수
13+ const dp : number [ ] = Array ( sLen ) . fill ( 0 ) ;
14+ dp [ 0 ] = isValid ( s [ 0 ] ) ? 1 : 0 ;
15+ dp [ 1 ] = ( isValid ( s [ 1 ] ) ? dp [ 0 ] : 0 ) + ( isValid ( s . substring ( 0 , 2 ) ) ? 1 : 0 ) ;
16+
17+ for ( let i = 2 ; i < sLen ; i ++ ) {
18+ const singleDigitWays = isValid ( s [ i ] ) ? dp [ i - 1 ] : 0 ;
19+ const doubleDigitWays = isValid ( s [ i - 1 ] + s [ i ] ) ? dp [ i - 2 ] : 0 ;
20+
21+ dp [ i ] = singleDigitWays + doubleDigitWays ;
22+ }
23+
24+ return dp [ sLen - 1 ] ;
25+ }
Original file line number Diff line number Diff line change 1+ function maxSubArray ( nums : number [ ] ) : number {
2+ const numsLen = nums . length ;
3+ let currentSum = nums [ 0 ] ;
4+ let maxSum = nums [ 0 ] ;
5+
6+ for ( let i = 1 ; i < numsLen ; i ++ ) {
7+ currentSum = Math . max ( currentSum + nums [ i ] , nums [ i ] ) ;
8+ maxSum = Math . max ( maxSum , currentSum ) ;
9+ }
10+
11+ return maxSum ;
12+ }
Original file line number Diff line number Diff line change 1+ function hammingWeight ( n : number ) : number {
2+ const RADIX = 2 ;
3+
4+ return n . toString ( RADIX ) . match ( / 1 / g) ?. length || 0 ;
5+ }
Original file line number Diff line number Diff line change 1+ function isPalindrome ( s : string ) : boolean {
2+ const converted = s . toLowerCase ( ) . replace ( / [ ^ a - z \d ] / g, "" ) ;
3+
4+ let l = 0 ;
5+ let r = converted . length - 1 ;
6+
7+ while ( l < r ) {
8+ if ( converted [ l ] !== converted [ r ] ) return false ;
9+ l ++ ;
10+ r -- ;
11+ }
12+
13+ return true ;
14+ }
You can’t perform that action at this time.
0 commit comments