首页 > 其他 > 详细

力扣——组合

时间:2019-03-07 21:22:00      阅读:171      评论:0      收藏:0      [点我收藏+]

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

示例:

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

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        LinkedList<List<Integer>> outList = new LinkedList<>();
        outList.add(new LinkedList<>());
        for (int i = 0; i < k; i++) {
            int listSize = outList.size();
            for (int j = 0; j < listSize; j++) {
                List<Integer> tlist = outList.pop();
                int fromIndex = 0;
                if (tlist.size() > 0){
                    fromIndex = tlist.get(tlist.size()-1);
                }
                for (int l = fromIndex+1; l <= n; l++) {
                    List ttlist = new LinkedList(tlist);
                    ttlist.add(l);
                    outList.add(ttlist);
                }
            }
        }
        return outList;
    }
}

 

力扣——组合

原文:https://www.cnblogs.com/JAYPARK/p/10492260.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!