zoukankan      html  css  js  c++  java
  • Combinations

    1. Title

    Combinations

    2. Http address

    https://leetcode.com/problems/combinations/

    3. The question

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

    For example,
    If n = 4 and k = 2, a solution is:

    [
      [2,4],
      [3,4],
      [2,3],
      [1,2],
      [1,3],
      [1,4],
    ]

    4. My code(AC)

     1 // Accepted
     2        public List<List<Integer>> combine(int n, int k) {
     3            List<List<Integer>>  result = new ArrayList<List<Integer>>();
     4            List<Integer> subList = null;
     5            for(int begin = 1;  begin <= n; begin++)
     6            {
     7                subList = new ArrayList<Integer>();
     8                subList.add(begin);
     9                getCombinations(begin + 1, n, k, subList, result);
    10            }
    11           return result;
    12         }
    13        
    14        public void getCombinations(int begin, int end, int k, List<Integer> subResult, List<List<Integer>> result)
    15        {
    16            
    17            if( subResult.size() == k)
    18            {
    19                 result.add(new ArrayList<Integer>(subResult));
    20                return;
    21            }
    22            for(int i = begin ; i <= end ; i++)
    23            {
    24                subResult.add(i);
    25                getCombinations(i + 1, end, k , subResult, result);
    26                subResult.remove(subResult.size() - 1);
    27            }
    28        }
  • 相关阅读:
    POJ3613 k边最短路
    洛谷4014最大/小费用最大流
    POJ1734无向图求最小环
    洛谷4013数字梯形
    洛谷4147玉蟾宫
    洛谷4145上帝造题的七分钟2
    洛谷4092 树
    Nginx动静分离-tomcat
    nginx之Geoip读取地域信息模块
    Nginx与Lua开发
  • 原文地址:https://www.cnblogs.com/ordili/p/4969961.html
Copyright © 2011-2022 走看看