Leetcode之Combination SumII
2016-01-16 23:04
211 查看
与Combination Sum不同之处在candidates数组中的元素最多只能用一次,且结果集必须不含有重复元素,方法为:
当前元素跟前一个元素是相同的时候,如果前一个元素被取了,那当前元素可以被取,也可以不取,反过来如果前一个元素没有取,那我们这个以及之后的所以相同元素都不能被取。
当前元素跟前一个元素是相同的时候,如果前一个元素被取了,那当前元素可以被取,也可以不取,反过来如果前一个元素没有取,那我们这个以及之后的所以相同元素都不能被取。
class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ result = [] lenofcan = len(candidates) if lenofcan == 0: return result currentresult = [] index = 0 candidates.sort() self.backtracking(candidates, index, target, result, currentresult, lenofcan) return result def backtracking(self, candidates, index, lefttarget, result, currentresult, lenofcan): if lefttarget == 0: result.append(currentresult) return if index > lenofcan - 1: return factor = lefttarget / candidates[index] if factor == 0: return copylefttarget = lefttarget for i in range(2): skip = 1 copycurrentresult = copy.deepcopy(currentresult) copylefttarget = lefttarget - i * candidates[index] if i == 1: copycurrentresult.append(candidates[index]) if i == 0: while index + skip < lenofcan and candidates[index] == candidates[index + skip]: skip += 1 self.backtracking(candidates, index + skip, copylefttarget, result, copycurrentresult, lenofcan)
相关文章推荐
- TOMCAT优化内存设置
- $(MAKE) , make命令
- JDK各个版本的新特性jdk1.5-jdk8
- 环境之于人
- 蓝懿ios技术交流和心得分享16.1.16
- 最大公共子序列求和问题(MCSS)
- android141 360 安装软件管理
- Android 反编译工具下载
- Flash学习记录1
- tomcat设置JDK
- bzoj1047 理想的正方形
- 大佬的1999年:刘强东卖光碟 马云要和硅谷较量
- win8+xp 双系统设定时的一点问题
- oracle笔记整理14——性能调优之oracle执行计划
- SS_关于n的n次方
- 从头认识java-17.6 Callable、Future和FutureTask
- 微信支付-我遇到的那些问题
- 为什么跳槽加薪会比内部调薪要高?
- 【iOS开发】CoreText的使用(1)
- 数据结构(线性表,队列,栈,树,图)(Unfinished)