LeetCode 10.7 Combination Sum
2016-04-26 15:08
337 查看
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where
the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
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:
c43e
import java.util.Stack;
public class T3 {
public static void main(String[] args) { int[] arr= {2 ,3 ,6 ,7}; T3 t=new T3(); t.DFS(arr, 7); t.print(); } Stack<int [] > ans=new Stack<>(); int n=0; int[] f=new int[1000]; int pre=0; void DFS(int[] v,int sum){ if(sum==0){ int[] arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=f[i]; } ans.push(arr); }else{ for(int i=pre;i<v.length;i++){ if(sum-v[i]>=0){ pre=i; f[n++]=v[i]; DFS(v,sum-v[i]); n--; } } } } void print(){ int num=1; while(!ans.isEmpty()){ System.out.println("======"+num+"====="); int []temp=ans.pop(); for(int i=0;i<temp.length;i++){ System.out.print(temp[i]+" "); } System.out.println(); num++; } }}
the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
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
2,3,6,7and target
7,
A solution set is:
c43e
[7]
[2, 2, 3]
import java.util.Stack;
public class T3 {
public static void main(String[] args) { int[] arr= {2 ,3 ,6 ,7}; T3 t=new T3(); t.DFS(arr, 7); t.print(); } Stack<int [] > ans=new Stack<>(); int n=0; int[] f=new int[1000]; int pre=0; void DFS(int[] v,int sum){ if(sum==0){ int[] arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=f[i]; } ans.push(arr); }else{ for(int i=pre;i<v.length;i++){ if(sum-v[i]>=0){ pre=i; f[n++]=v[i]; DFS(v,sum-v[i]); n--; } } } } void print(){ int num=1; while(!ans.isEmpty()){ System.out.println("======"+num+"====="); int []temp=ans.pop(); for(int i=0;i<temp.length;i++){ System.out.print(temp[i]+" "); } System.out.println(); num++; } }}
相关文章推荐
- (4.3.2.2)ListView 动态设置高度问题
- (4.3.2.1)Android ListView点击展开收起效果(一)
- ElasticSearch学习14_elasticsearch 口水篇(3)java客户端 - Jest
- Window系统部署在本地的IIS7里以后,结果不能访问承载SL的.aspx页面
- 【51NOD 1478】括号序列的最长合法子段
- .Net实现微信公众平台开发接口(二) 之 “获取access_token”
- word2007怎么转换成pdf格式
- Golang的TLS通信,证书文件使用.
- 记录linux软件源代理服务器设置方法
- 最全面的 Android 编码规范指南
- 让屏幕保持竖屏
- 'net’ 不是内部命令或外部命令,也不是可运行的程序或批处理文件
- 百度地图问题汇总
- UE3名称结构(Name)
- 文件管理 - 1
- 给 Android 开发者的 RxJava 详解
- javascript处理HTML的Encode(转码)和Decode(解码)总结
- Java相对路径读取文件
- 【java线程系列】java线程系列之线程间的交互wait()/notify()/notifyAll()及生产者与消费者模型
- cocos2dx 创建精灵的5种方式