高级农民
- 积分
- 1275
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-7-6
- 最后登录
- 1970-1-1
|
Day 3
今天起床比较晚。吃了两片面包。开始刷,等下出去玩。
这里把一系列的combination都做掉好了。
10:09AM - 10:26AM
https://leetcode.com/problems/combination-sum/
- class Solution(object):
- def combinationSum(self, candidates, target):
- """
- :type candidates: List[int]
- :type target: int
- :rtype: List[List[int]]
- """
- res = []
- def dfs(index, current, target):
- if target == 0:
- res.append(list(current))
- if target < 0:
- return
- for i in range(index, len(candidates)):
- current.append(candidates[i])
- dfs(i, current, target-candidates[i])
- current.pop()
- dfs(0, [], target)
- return res
复制代码
10:26AM - 10:29AM
https://leetcode.com/problems/combinations/
- class Solution(object):
- def combine(self, n, k):
- """
- :type n: int
- :type k: int
- :rtype: List[List[int]]
- """
- res = []
-
- def dfs(index, current):
- if len(current) == k:
- res.append(list(current))
- for i in range(index+1, n+1):
- current.append(i)
- dfs(i, current)
- current.pop()
- dfs(0, [])
- return res
-
复制代码
https://leetcode.com/problems/combination-sum-ii/
10:29AM - 11:05AM
这道题和之前的combination sum最大的区别是不能有重复的数字。
- class Solution(object):
- def combinationSum2(self, candidates, target):
- """
- :type candidates: List[int]
- :type target: int
- :rtype: List[List[int]]
- """
- candidates = sorted(candidates)
- res = []
- print(candidates)
- def dfs(index, current, target):
- if target == 0:
- res.append(list(current))
- if target < 0:
- return
- for i in range(index, len(candidates)):
- if candidates[i] > target:
- break
- if i > index and candidates[i] == candidates[i-1]:
- continue
- current.append(candidates[i])
- dfs(i+1, current, target-candidates[i])
- current.pop()
- dfs(0, [], target)
- return res
-
复制代码
https://leetcode.com/problems/combination-sum-iii/
11:06AM - 11:13AM
- class Solution(object):
- def combinationSum3(self, k, n):
- """
- :type k: int
- :type n: int
- :rtype: List[List[int]]
- """
- res = []
-
- def dfs(current_number, current, target):
- if target == 0 and len(current) == k:
- res.append(list(current))
- if target < 0 or len(current) >= k:
- return
- for i in range(current_number, 10):
- if i > target:
- break
- dfs(i+1, current+[i], target-i)
- dfs(1, [], n)
- return res
-
-
-
复制代码
|
|