LeetCode0077.组合

版权声明:啦啦啦,不用于商业的话随便拿,记得带上博客地址http://blog.csdn.net/wjoker https://blog.csdn.net/wjoker/article/details/84240199

0077.组合

描述

给定两个整数 nk,返回 1 … *n *中所有可能的 k 个数的组合。

实例

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

题解

  • 广度遍历
  • nowIndex记录当前已经确定的数量
  • nowNum记录已经确定的最大数字
  • k-nowIndex-1 > n-nowNum用于判断当前数字是否过大
public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new LinkedList<>();
        int[] nowList = new int[k];

        allCombine(n,k,-1,0,nowList,result);
        return result;
    }

    public void allCombine(int n,int k,int nowIndex,int nowNum,int[] nowList,List<List<Integer>> result){
        if (nowIndex == k-1){
            //添加结果
            List<Integer> list = new ArrayList<>();
            for (int i:nowList)
                list.add(i);
            result.add(list);
            return;
        }

        if (k-nowIndex-1 > n-nowNum){
            return;
        }

//        if (nowNum == n){
//            return;
//        }

        for (int i = nowNum+1; i <= n; i++) {
            int[] thisList = nowList.clone();
            thisList[nowIndex+1] = i;
            allCombine(n,k,nowIndex+1,i,thisList,result);
        }
    }

猜你喜欢

转载自blog.csdn.net/wjoker/article/details/84240199