public class Solution
{
List<IList<int>> list = new List<IList<int>>();//全部记录
List<int> records = new List<int>();//一条记录
bool bk = false;
private void BackTrack(List<int> candidates, int target, int sum)
{
if (sum == target)
{
int[] temp = new int[records.Count];
records.CopyTo(temp);
bool same = false;
foreach (var l in list)
{
if (l.Count == temp.Length)
{
var l1 = l.OrderBy(x => x).ToList();
var l2 = temp.OrderBy(x => x).ToList();
var samecount = ;
for (int x = ; x < l1.Count; x++)
{
if (l1[x] == l2[x])
{
samecount++;
}
}
if (samecount == l.Count)
{
same = true;
break;
}
}
}
if (!same)
{
list.Add(temp.ToList());
}
bk = true;
return;
}
else if (sum < target)
{
bk = true;
for (int position = ; position < candidates.Count; position++)
{
var cur = candidates[position];
sum += cur;
records.Add(cur);
BackTrack(candidates, target, sum);
//回溯
records.RemoveAt(records.Count - );
sum -= cur;
if (bk)
{
bk = false;
break;
}
}
}
else
{
bk = true;
return;
}
} public IList<IList<int>> CombinationSum(int[] candidates, int target)
{
var can = candidates.OrderBy(x => x).ToList();
BackTrack(can, target, );
return list;
}
}

补充一个python的实现,写的要简单的多了:

 class Solution:
def dfs(self,candidates,target,index,path,l):
if target < 0:
return
elif target == 0:
l.append(path)
return
for i in range(index,len(candidates)):
self.dfs(candidates,target-candidates[i],i,path+[candidates[i]],l)
return def combinationSum(self, candidates: 'List[int]', target: 'int') -> 'List[List[int]]':
l = list()
path = []
candidates.sort()
self.dfs(candidates,target,0,path,l)
return l

最新文章

  1. Android 全局获取 Context 与使用 Intent 传递对象
  2. myeclipse 10打开status.xml 卡死
  3. [转载] Android Metro风格的Launcher开发系列第一篇
  4. JVM 垃圾回收算法
  5. python中struct模块及packet和unpacket
  6. SVN资料库转移-----dump和load
  7. Tomcat8 配置Oracle11g数据源
  8. ios7以上自定义导航栏标题的字体大小及颜色的方法
  9. Common Lisp Style Guide - Ariel Networks Labs
  10. 【C#多线程编程实战笔记】一、 线程基础
  11. Java 大数类BigInteger和BigDecimal的基本函数
  12. 在MVC中Dashboard基础入门操作
  13. JavaScript 包装对象
  14. google 变量命名规则简要记录
  15. RedHat6.5系统LVM增加新硬盘实现根文件系统扩容
  16. python模块:pickle
  17. [hadoop读书笔记] 第十五章 sqoop1.4.6小实验 - 数据在mysq和hdfs之间的相互转换
  18. C# winform webbrowser如何指定内核为IE11? 输出 this.webbrowser.Version 显示版本是IE11的,但实际版本不是啊! 网上打的修改注册表HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULA
  19. pyDay11
  20. OA项目中的论坛模块设计与实现

热门文章

  1. Debian下安装docker
  2. python day21 ——面向对像-反射 getattr,内置方法
  3. springBoot的数据库操作
  4. 多线程callable使用方法
  5. ASP.NET之使用Ajax实现页面异步刷新(无需刷新整个页面)
  6. jQuery-2.DOM---jQuery遍历
  7. php批量检测和去掉bom头(转)
  8. 【leetcode】438. Find All Anagrams in a String
  9. Linux搭建SVN环境
  10. android用户信息保存