File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # https://leetcode.com/problems/combination-sum/
2+
3+ # for문으로 해결이 되지 않아 gpt 도움을 받아 해결하였습니다.
4+ # 같은 숫자를 재사용하면서, 순서를 고정해서 중복 없는 조합을 DFS로 탐색하는 구조
5+ # 시간 복잡도 : O(2^n) (백트래킹 탐색)
6+ # 공간 복잡도 : O(target) (재귀 깊이)
7+
8+ class Solution (object ):
9+ def combinationSum (self , candidates , target ):
10+
11+ result = []
12+
13+ def dfs (start , path , total ):
14+ # 종료 조건 1 : target을 맞춘 경우
15+ if total == target :
16+ result .append (path [:])
17+ return
18+
19+ # 종료 조건 2 : target 초과한 경우
20+ if total > target :
21+ return
22+
23+ # 후보 탐색 -> 같은 방향으로만 탐색
24+ for i in range (start , len (candidates )):
25+ # 같은 숫자 재사용 가능 -> i를 그대로 넘기기
26+ dfs (i , path + [candidates [i ]], total + candidates [i ]) # 새로운 리스트 만들어서 전달
27+
28+
29+ dfs (0 , [], 0 )
30+
31+ return result
Original file line number Diff line number Diff line change 1+ # https://leetcode.com/problems/decode-ways
2+
3+ class Solution (object ):
4+ def numDecodings (self , s ):
5+ if not s or s [0 ] == '0' :
6+ return 0
7+
8+ n = len (s )
9+
10+ # dp[i] = i번째까지 문자열을 해석하는 방법의 개수
11+ dp = [0 ] * (n + 1 )
12+ dp [0 ] = 1
13+ dp [1 ] = 1
14+
15+ for i in range (2 , n + 1 ):
16+ # 1자리 체크
17+ if s [i - 1 ] != '0' :
18+ dp [i ] += dp [i - 1 ]
19+
20+ # 2자리 체크
21+ two_digit = int (s [i - 2 :i ])
22+ if 10 <= two_digit <= 26 :
23+ dp [i ] += dp [i - 2 ]
24+
25+ return dp [n ]
Original file line number Diff line number Diff line change 1+ # https://leetcode.com/problems/maximum-subarray/
2+
3+ # 이전까지 누적한 값이 음수면 버리고 현재 값부터 다시 시작
4+ # 한 번만 순회 -> O(n)
5+
6+ class Solution (object ):
7+ def maxSubArray (self , nums ):
8+ current_sum = nums [0 ]
9+ max_sum = nums [0 ]
10+
11+ for i in range (1 , len (nums )):
12+ current_sum = max (nums [i ], current_sum + nums [i ])
13+ max_sum = max (max_sum , current_sum )
14+
15+ return max_sum
Original file line number Diff line number Diff line change 1+ # https://leetcode.com/problems/number-of-1-bits
2+
3+ class Solution (object ):
4+ def hammingWeight (self , n ):
5+ binary = bin (n )[2 :]
6+ return len (str (binary ).replace ('0' , '' ))
Original file line number Diff line number Diff line change 1+ # https://leetcode.com/problems/valid-palindrome
2+
3+ # re.sub -> O(n)
4+ # lower() -> O(n)
5+ # reverse -> O(n)
6+ # 최종 시간 복잡도 : O(n) + O(n) + O(n) + O(n) = O(n)
7+
8+ # s_pali -> 최대 O(n)
9+ # s_pali_reverse -> O(n)
10+ # 최종 공간 복잡도 : O(n)
11+
12+ import re
13+
14+ class Solution (object ):
15+ def isPalindrome (self , s ):
16+ s_pali = re .sub (r'[^a-zA-Z0-9]' , '' , s ).lower ()
17+ s_pali_reverse = s_pali [::- 1 ]
18+
19+ if s_pali == s_pali_reverse :
20+ return True
21+ else :
22+ return False
You can’t perform that action at this time.
0 commit comments