代码随想录第28天|93. 复原 IP 地址、78. 子集、90. 子集 II

66 阅读1分钟

93. 复原 IP 地址

1. first idea

When we judge a node is legal, there are 2 conditions:

  1. the node value is less than 256.
  2. the number of left characters is less than the 3×(4levelcurrent)3\times (4-level_{current}).

Recursion Logic:

  1. stop condition: the left characters are run out.
  2. current level: for i in range(1, 3) the substring, judge wether the tmp_str[:i] is legal or not.
  3. params: tmp_str, level_num.
class Solution:
    def __init__(self):
        self.res_list = []

    def track_back(self, tmp_str_list, level_num, tmp_ip):
        if len(tmp_str_list) == 0 and level_num == 4:
            self.res_list.append(tmp_ip[1:])
        else:
            for i in range(1, min(4, len(tmp_str_list) + 1)):
                # print(tmp_str_list[:i], tmp_str_list[i:])
                if (int("".join(tmp_str_list[:i])) < 256) and (len(tmp_str_list[i:]) <= (3 * (3 - level_num))):
                    # print(True)
                    if (len(tmp_str_list[:i]) > 1) and (tmp_str_list[0] == '0'):
                        continue
                    self.track_back(tmp_str_list[i:], level_num + 1, tmp_ip + "." + "".join(tmp_str_list[:i]))

    def restoreIpAddresses(self, s: str) -> List[str]:
        self.track_back(list(s), 0, "")
        return self.res_list

78. 子集

1. first idea

My first idea is to for cycle along with length.

One level is:

for i in range(1, len(left_nums)):
    tmp_list.append(left_nums[:i])
    recursion for (left_nums[i:])

This is wrong, because if the nums are 1, 2, 3, we can only get [1], [2, 3] but not [2], [1, 3].

2. reading doc

代码随想录 (programmercarl.com) image.png

3. learning time

1h30min.

90. 子集 II

1. first idea

  1. sort the list first.
  2. when for idx in range(len(left_nums)), if the (idx > start_idx) and nums[idx] == nums[start_idx], skip this node.
class Solution:
    def __init__(self):
        self.res_list = []

    def trace_back(self, left_nums, tmp_list):
        if len(left_nums) == 0:
            return
        else:
            record_list = []
            for i in range(len(left_nums)):
                if left_nums[i] not in record_list:
                    record_list.append(left_nums[i])
                else:
                    continue
                self.res_list.append(tmp_list + [left_nums[i]])
                self.trace_back(left_nums[(i + 1):], tmp_list + [left_nums[i]])

    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        self.trace_back(nums, [])
        self.res_list.append([])
        return self.res_list

2. learning time

20mins.