예제 #1
0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List

import validator


class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        def search(cur_nums: List[int], start_index: int, total_count: int):
            if len(cur_nums) == total_count:
                result.append(cur_nums[:])
                return
            for i in range(start_index, len(nums)):
                cur_nums.append(nums[i])
                search(cur_nums, i + 1, total_count)
                cur_nums.remove(nums[i])

        result = []
        for n in range(len(nums) + 1):
            search([], 0, n)
        return result


if __name__ == '__main__':
    validator.validate_without_order(Solution().subsets(
        [1, 2, 3]), [[1], [3], [2], [1, 2, 3], [1, 3], [2, 3], [1, 2], []])
예제 #2
0

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        def backtracking(cur_nums=[], leaving=n, cur_idx=1):
            len_cur = len(cur_nums)
            if len_cur == k:
                if leaving == 0:
                    result.append(cur_nums)
                return
            for i in range(cur_idx, 10):
                if (leaving - i < 0) or (10 - i < k - len_cur) or (leaving > leaving_sum[10 - k + len_cur]):
                    # condition1: leaving比i小,后续任意数字加上都会超
                    # condition2: 剩余数字全选上,总数量仍然达不到预期数量n;
                    # condition3: 剩余数字总和 > sum(i,9),即 全部加上也达不到leaving
                    break
                backtracking(cur_nums + [i], leaving - i, i + 1)

        leaving_sum = [0, 45, 44, 42, 39, 35, 30, 24, 17, 9]
        result = []
        backtracking()
        return result


if __name__ == '__main__':
    validator.validate_without_order(Solution().combinationSum3(3, 7), [[1, 2, 4]])
    validator.validate_without_order(Solution().combinationSum3(3, 9), [[1, 2, 6], [1, 3, 5], [2, 3, 4]])
    validator.validate_without_order(Solution().combinationSum3(3, 100), [])
    validator.validate_without_order(Solution().combinationSum3(9, 46), [])
    validator.validate_without_order(Solution().combinationSum3(2, 6), [[1, 5], [2, 4]])
예제 #3
0
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List

import validator


class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        def backtracking(leaving_nums: List[int], cur_nums=list()):
            if len(leaving_nums) == 0:
                result.append(cur_nums[:])
                return
            for num in leaving_nums:
                cur_nums.append(num)
                ori_index = leaving_nums.index(num)
                leaving_nums.remove(num)
                backtracking(leaving_nums, cur_nums)
                leaving_nums.insert(ori_index, num)
                cur_nums.remove(num)

        result = []
        backtracking(nums)
        return result


if __name__ == '__main__':
    validator.validate_without_order(Solution().permute([1, 2, 3]),
                                     [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]])
예제 #4
0
            if leaving == 0:
                if nums not in result:
                    result.append(nums)
                return
            for i in range(cur_idx, len(candidates)):
                if leaving < candidates[i]:
                    break

                if i > cur_idx and candidates[i] == candidates[i - 1]:
                    continue
                backtracking(nums + [candidates[i]], leaving - candidates[i],
                             i + 1)

        result = list()
        candidates.sort()
        backtracking()
        return result


if __name__ == '__main__':
    validator.validate_without_order(
        Solution().combinationSum2([10, 1, 2, 7, 6, 1, 5], 8),
        [[1, 7], [1, 2, 5], [2, 6], [1, 1, 6]])
    validator.validate_without_order(
        Solution().combinationSum2([2, 5, 2, 1, 2], 5), [[1, 2, 2], [5]])
    print(Solution().combinationSum2([
        29, 19, 14, 33, 11, 5, 9, 23, 23, 33, 12, 9, 25, 25, 12, 21, 14, 11,
        20, 30, 17, 19, 5, 6, 6, 5, 5, 11, 12, 25, 31, 28, 31, 33, 27, 7, 33,
        31, 17, 13, 21, 24, 17, 12, 6, 16, 20, 16, 22, 5
    ], 28))
예제 #5
0

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums1_count = collections.Counter(nums1)
        result = []
        for i in range(len(nums2)):
            if nums1_count.get(nums2[i], 0) > 0:
                result.append(nums2[i])
                nums1_count[nums2[i]] -= 1
        return result

    def intersectV2(self, nums1: List[int], nums2: List[int]) -> List[int]:
        if len(nums1) > len(nums2):
            return self.intersect(nums2, nums1)

        result = []
        for i in range(len(nums1)):
            if not nums2:
                break
            if nums1[i] in nums2:
                result.append(nums1[i])
                nums2.remove(nums1[i])
        return result


if __name__ == '__main__':
    validate_without_order(Solution().intersect([4, 9, 5], [9, 4, 9, 8, 4]),
                           [4, 9])
    validate_without_order(Solution().intersect([1, 2, 2, 1], [2, 2]), [2, 2])
예제 #6
0
        for len1 in range(3):
            for len2 in range(3):
                for len3 in range(3):
                    len4 = len_s - len1 - len2 - len3 - 3
                    if len4 < 1 or len4 > 3:
                        continue
                    part1, part2, part3, part4 = s[:len1 + 1], s[len1 + 1: len1 + len2 + 2], \
                                                 s[len1 + len2 + 2: len1 + len2 + len3 + 3], s[len1 + len2 + len3 + 3:]
                    if (len(part1) > 1 and part1[0] == '0') or (len(part2) > 1 and part2[0] == '0') \
                            or (len(part3) > 1 and part3[0] == '0') or (len(part4) > 1 and part4[0] == '0'):
                        continue
                    if int(part1) <= 255 and int(part2) <= 255 and int(
                            part3) <= 255 and int(part4) <= 255:
                        result.append('.'.join([part1, part2, part3, part4]))
        return result


if __name__ == '__main__':
    validator.validate_without_order(
        Solution().restoreIpAddresses("25525511135"),
        ["255.255.11.135", "255.255.111.35"])
    validator.validate_without_order(Solution().restoreIpAddresses("0000"),
                                     ["0.0.0.0"])
    validator.validate_without_order(Solution().restoreIpAddresses("1111"),
                                     ["1.1.1.1"])
    validator.validate_without_order(Solution().restoreIpAddresses("010010"),
                                     ["0.10.0.10", "0.100.1.0"])
    validator.validate_without_order(
        Solution().restoreIpAddresses("101023"),
        ["1.0.10.23", "1.0.102.3", "10.1.0.23", "10.10.2.3", "101.0.2.3"])