File tree Expand file tree Collapse file tree 5 files changed +88
-0
lines changed
Expand file tree Collapse file tree 5 files changed +88
-0
lines changed Original file line number Diff line number Diff line change 1+ # idea: brute force
2+ # Complexity: O(len(candidates)^(target / min(candidates)))
3+
4+ class Solution :
5+ def combinationSum (self , candidates : List [int ], target : int ) -> List [List [int ]]:
6+ candidates .sort ()
7+ result = []
8+ nums = []
9+
10+ def dfs (start : int , total : int ):
11+ if total > target :
12+ return
13+ if total == target :
14+ result .append (nums .copy ())
15+ return
16+ for i in range (start , len (candidates )):
17+ num = candidates [i ]
18+ if total + num > target :
19+ break
20+ nums .append (num )
21+ dfs (i , total + num )
22+ nums .pop ()
23+ dfs (0 , 0 )
24+ return result
25+
26+
27+
Original file line number Diff line number Diff line change 1+ # idea : Tree
2+ class Solution :
3+ def numDecodings (self , s : str ) -> int :
4+ # recurisve : top-down
5+ # DP : bottom-up can be another way to solve it, but it is not clear for me.
6+ memo = {len (s ):1 }
7+ def dfs (start ):
8+ if start in memo :
9+ return memo [start ]
10+ if s [start ] == '0' :
11+ memo [start ] = 0
12+ elif start + 1 < len (s ) and int (s [start :start + 2 ]) < 27 :
13+ memo [start ] = dfs (start + 1 ) + dfs (start + 2 )
14+ else :
15+ memo [start ] = dfs (start + 1 )
16+ return memo [start ]
17+ return dfs (0 )
18+
19+
Original file line number Diff line number Diff line change 1+ # idea : DP
2+ class Solution :
3+ def maxSubArray (self , nums : List [int ]) -> int :
4+ # The solution must run in O(N^2) or better.
5+ '''
6+ 1. Idea: Sorting + Two Pointers (x) — This problem does not allow changing the original order of the array.
7+ 2. Subarrays (TLE) — O(N^3), too slow.
8+ 3. DP (o)
9+ '''
10+ max_total = nums [0 ]
11+ total = nums [0 ]
12+ # dp = [0]*len(nums)
13+ # dp[0] = nums[0]
14+ for i in range (1 ,len (nums )):
15+ # dp[i] = max(nums[i], dp[i-1]+nums[i])
16+ total = max (nums [i ], total + nums [i ])
17+ max_total = max (total , max_total )
18+ return max_total
19+
20+
21+
Original file line number Diff line number Diff line change 1+ # idea: -
2+
3+ from collections import Counter
4+ class Solution :
5+ def hammingWeight (self , n : int ) -> int :
6+ bits = bin (n ).split ('0b' )[- 1 ]
7+ return Counter (bits )['1' ]
8+
9+
10+
Original file line number Diff line number Diff line change 1+ # idea : regex
2+ import re
3+
4+ class Solution :
5+ def isPalindrome (self , s : str ) -> bool :
6+ alphabet = re .sub (r'[^A-Za-z0-9]' , '' , s ).lower ()
7+
8+ return alphabet == alphabet [::- 1 ]
9+
10+
11+
You can’t perform that action at this time.
0 commit comments