77.Combinations

25 年 7 月 24 日 星期四
153 字
1 分钟

77. Combinations

python
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        ans = []
        path = []

        # reverse enumerate
        def dfs(i):
            d = k - len(path)
            if i < d:
                return
            if len(path) == k:
                ans.append(path[:])
                return

            for j in range(i, 0, -1):
                path.append(j)
                dfs(j-1)
                path.pop()
        dfs(n)
        return ans

forward enumerate

python
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        ans = []
        path = []

        # answer perspective
        def dfs(i):
            # pruning
            if k - len(path) > n - i + 1:
                return
            if len(path) == k:
                ans.append(path[:])
                return
            if i == n+1:
                return
            for j in range(i, n+1):
                path.append(j)
                dfs(j+1)
                path.pop()
        dfs(1)
        return ans

choose or not

python
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        ans = []
        path = []

        # choose or not
        def dfs(i):
            if len(path) == k:
                ans.append(path[:])
                return
            if i == n+1:
                return
            # not choose
            dfs(i+1)

            # choose
            path.append(i)
            dfs(i+1)
            path.pop()
        dfs(1)
        return ans

文章标题:77.Combinations

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/77combinations[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。