首页 > 其他 > 详细

LeetCode Combinations

时间:2016-09-07 17:31:35      阅读:179      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/googlemeoften/p/5850063.html

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