Skip to content

Add python solutions for problem 90, 92 #208

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Oct 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion problems/90.subsets-ii.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Output:

## 代码

* 语言支持:JS,C++
* 语言支持:JS,C++,Python3

JavaScript Code:

Expand Down Expand Up @@ -132,6 +132,32 @@ public:
}
};
```
Python Code:

```Python
class Solution:
def subsetsWithDup(self, nums: List[int], sorted: bool=False) -> List[List[int]]:
"""回溯法,通过排序参数避免重复排序"""
if not nums:
return [[]]
elif len(nums) == 1:
return [[], nums]
else:
# 先排序,以便去重
# 注意,这道题排序花的时间比较多
# 因此,增加一个参数,使后续过程不用重复排序,可以大幅提高时间效率
if not sorted:
nums.sort()
# 回溯法
pre_lists = self.subsetsWithDup(nums[:-1], sorted=True)
all_lists = [i+[nums[-1]] for i in pre_lists] + pre_lists
# 去重
result = []
for i in all_lists:
if i not in result:
result.append(i)
return result
```

## 相关题目

Expand Down
52 changes: 51 additions & 1 deletion problems/92.reverse-linked-list-ii.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ Output: 1->4->3->2->5->NULL

## 代码

语言支持:JS, C++
语言支持:JS, C++, Python3

JavaScript Code:

Expand Down Expand Up @@ -194,3 +194,53 @@ public:
}
};
```
Python Code:
```Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
"""采用先翻转中间部分,之后与不变的前后部分拼接的思路"""
# 处理特殊情况
if m == n:
return head

# 例行性的先放一个开始节点,方便操作
first = ListNode(0)
first.next = head

# 通过以下两个节点记录拼接点
before_m = first # 原链表m前的部分
after_n = None # 原链表n后的部分

# 通过以下两个节点记录翻转后的链表
between_mn_head = None
between_mn_end = None

index = 0
cur_node = first
while index < n:
index += 1
cur_node = cur_node.next
if index == m - 1:
before_m = cur_node
elif index == m:
between_mn_end = ListNode(cur_node.val)
between_mn_head = between_mn_end
elif index > m:
temp = between_mn_head
between_mn_head = ListNode(cur_node.val)
between_mn_head.next = temp
if index == n:
after_n = cur_node.next

# 进行拼接
between_mn_end.next = after_n
before_m.next = between_mn_head

return first.next
```