力扣——组合

给定两个整数 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;
    }
}

 

posted @ 2019-03-07 20:52  JAYPARK01  阅读(185)  评论(0编辑  收藏  举报