首页 > 代码库 > LeetCode Combinations

LeetCode Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1,2,...,n.

import java.util.ArrayList;import java.util.List;class Solution {    public List<List<Integer>> combine(int n, int k) {        return combine(1, n + 1, k);    }    public List<List<Integer>> combine(int low, int upper, int k) {        List<List<Integer>> result = new ArrayList<List<Integer>>();        if (k == 1) {            for (int i = low; i < upper; i++) {                List<Integer> r = new ArrayList<Integer>();                r.add(i);                result.add(r);            }            return result;        }        for (int i = low; i < upper; i++) {            List<List<Integer>> r = combine(i + 1, upper, k - 1);            for (List<Integer> a : r) {                a.add(0, i);            }            result.addAll(r);        }        return result;    }    public static void main(String[] args) {        Solution s = new Solution();        List<List<Integer>> lists = s.combine(4, 2);        for(List res :lists){            System.out.println(res);        }    }};

 

LeetCode Combinations