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