Combinations
来源:互联网 发布:java中数据类型转换 编辑:程序博客网 时间:2024/05/03 06:45
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]
典型的回溯法求解 代码如下:
public class Solution { public static List<List<Integer>> combine(int n, int k) {Map<Integer,Integer> map=new HashMap<Integer,Integer>();List<List<Integer>> res=new ArrayList<List<Integer>>();List<Integer> tmp=new ArrayList<Integer>();Combine(res, tmp, n, k, 0, map,1);return res;}public static void Combine(List<List<Integer>> res,List<Integer> tmp,int n,int k,int count,Map<Integer,Integer> map,int index){if(count==k){res.add(tmp);return;}for(int i=index;i<=n;i++){if(map.containsKey(i)) continue;Map<Integer,Integer> newMap=new HashMap<Integer,Integer>();newMap.putAll(map);newMap.put(i, 1);List<Integer> newTmp=new ArrayList<Integer>();newTmp.addAll(tmp);newTmp.add(i);Combine(res, newTmp, n, k, count+1, newMap,i);}}}
0 0
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Iwpriv工作流程及常用命令使用
- 【Linux】FTP文件下载
- Xcode xcconfig文件 常用编译选项设置
- opencv 2.3.1使用CvvImage 的方法(总结)
- 如何做好无极灯节能灯具销售
- Combinations
- Linux 获取文件大小--C函数
- 12种JavaScript MVC框架之比较
- 第17周项目3--胖子伤不起(初识结构体)
- UNIX网络编程之一、如何运行书籍自带源码
- java通过正则表达式获取文本中的浮点数
- 无线设备状态机(The Radio State Machine)
- 第十七周项目三 胖子伤不起
- win2003安装证书服务中遇到的问题