【LeetCode题意分析&解答】40. Combination Sum II
2016-03-18 23:48
417 查看
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
A solution set is:
题意分析:
本题是给定一个数字集合(可能有重复)和一个目标值,让你找出所有可能的组合,使之和为目标值。所有的数字只能使用一次,要求得到的组合不能有重复,并且组合里面的数字必须是升序。
解答:
对比一下【LeetCode题意分析&解答】39. Combination Sum,唯一的区别在于本题数字只能使用一次,而不是无限次。所以我们只需要对上一题的代码稍作修改,就可以实现本题的要求。
AC代码:
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
10,1,2,7,6,1,5and target
8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
题意分析:
本题是给定一个数字集合(可能有重复)和一个目标值,让你找出所有可能的组合,使之和为目标值。所有的数字只能使用一次,要求得到的组合不能有重复,并且组合里面的数字必须是升序。
解答:
对比一下【LeetCode题意分析&解答】39. Combination Sum,唯一的区别在于本题数字只能使用一次,而不是无限次。所以我们只需要对上一题的代码稍作修改,就可以实现本题的要求。
AC代码:
class Solution(object): def combinationSum2(self, candidates, target): ret_list = [] def backtracing(target, candidates, index, temp_list): if target == 0: ret_list.append(temp_list) elif target > 0: for i in xrange(index, len(candidates)): # remove duplicates if i != index and candidates[i] == candidates[i - 1]: continue backtracing(target - candidates[i], candidates, i + 1, temp_list + [candidates[i]]) backtracing(target, sorted(candidates), 0, []) return ret_list
相关文章推荐
- javaWeb项目如何添加jar包
- Android常用权限permission列表摘录
- 高精度求平方根
- 枚举类型互相转换(使用GetEnumName和TypeInfo两个函数)
- iOS GCD学习笔记
- 机房收费系统遇到的问题(二) 逆向思维,消费时间不是相减,而是递增
- 蓝桥杯-横向打印二叉树(模拟)
- 关于对象列表遍历问题。
- Oculus Rift, HTC Vive, SONY PSVR的全面对比
- 使用CSS3美化复选框checkbox
- Dialog实现BottomSheet设计
- 237. Delete Node in a Linked List
- animate dong
- 发布你的Python模块
- PO J2602 大数相加
- 文章标题
- uva285 - Longest Run on a Snowboard(二维最长递增子序列)
- 网易互娱2017实习生招聘在线笔试(一)
- 高精度进制转换
- Oracle 队列锁类型 Oracle Enqueue Lock Type Reference including 11g new locks