File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed
longest-increasing-subsequence Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ # https://leetcode.com/problems/longest-increasing-subsequence/
2+
3+ from typing import List
4+
5+ class Solution :
6+ def lengthOfLIS_dp (self , nums : List [int ]) -> int :
7+ """
8+ [Complexity]
9+ - TC: O(n^2)
10+ - SC: O(n)
11+
12+ [Approach]
13+ dp[i] = nums[i]๊ฐ ํฌํจ๋๋ LIS์ ์ต๋ ๊ธธ์ด
14+ """
15+ n = len (nums )
16+ dp = [1 ] * n
17+
18+ for i in range (n ):
19+ for j in range (i ):
20+ if nums [j ] < nums [i ]:
21+ dp [i ] = max (dp [i ], dp [j ] + 1 )
22+
23+ return max (dp )
24+
25+ def lengthOfLIS (self , nums : List [int ]) -> int :
26+ """
27+ [Complexity]
28+ - TC: O(nlogn) (w. binary search)
29+ - SC: O(n)
30+
31+ [Approach]
32+ ref: https://leetcode.com/problems/longest-increasing-subsequence/solutions/1326308/c-python-dp-binary-search-bit-segment-tree-solutions-picture-explain-o-nlogn
33+ nums๋ฅผ ์์ฐจ์ ์ผ๋ก ์ํํ๋ฉฐ LIS๋ฅผ ๋ชจ์๋ค. ์ด๋,
34+ - ํ์ฌ ๋ณด๊ณ ์๋ ์์ n์ด LIS์ ๋ง์ง๋ง ์์ ์ดํ๋ผ๋ฉด: LIS์ ์์ ์ค (1) n ์ด์์ด๋ฉด์ (2) ์ต์๊ฐ์ ์์น์ n ๋ฎ์ด์ฐ๊ธฐ
35+ - ๊ทธ ์ธ์ ๊ฒฝ์ฐ๋ผ๋ฉด: LIS์ ๋งจ ๋์ num append
36+ ํ๋ค.
37+ LIS๋ ์ ๋ ฌ๋์ด ์์ ๊ฒ์ด๋ฏ๋ก binary search๋ฅผ ์ด์ฉํ ์ ์์ผ๋ฉฐ, ์ด๋ ๊ฒ ๊ตฌ์ฑํ LIS์ ๊ธธ์ด๊ฐ ์ต๋ ๊ธธ์ด์ด๋ค.
38+ """
39+
40+ def find_leftmost_idx (lis , n ):
41+ lo , hi = 0 , len (lis ) - 1
42+
43+ while lo < hi :
44+ mid = lo + (hi - lo ) // 2
45+ if lis [mid ] < n : # -- ์์ ์ ์ธํ๋ ๊ฒฝ์ฐ: n ๋ฏธ๋ง์ธ ๊ฒฝ์ฐ
46+ lo = mid + 1
47+ else :
48+ hi = mid
49+
50+ return lo
51+
52+ lis = []
53+
54+ for n in nums :
55+ # ํ์ฌ ๋ณด๊ณ ์๋ n์ด LIS์ ๋ง์ง๋ง ์์ ์ดํ๋ผ๋ฉด
56+ if lis and n <= lis [- 1 ]:
57+ lis [find_leftmost_idx (lis , n )] = n
58+ # ๊ทธ ์ธ์ ๊ฒฝ์ฐ๋ผ๋ฉด
59+ else :
60+ lis .append (n )
61+
62+ return len (lis )
You canโt perform that action at this time.
0 commit comments