LeetCode Combinations

Posted googlemeoften

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

个人记录-LeetCode 77. Combinations

leetcode-Combinations-77

[Lintcode]152. Combinations/[Leetcode]77. Combinations

LeetCode(17)Letter Combinations of a Phone Number

leetcode17. Letter Combinations of a Phone Number

#Leetcode# 77. Combinations