zoukankan      html  css  js  c++  java
  • leetcode -- Combinations

    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],
    ]
     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> combine(int n, int k) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
     6         if(k == 0){
     7             return result;
     8         }
     9         
    10         ArrayList<Integer> com = new ArrayList<Integer>();
    11         int depth = 1;
    12         generate(result, com, depth, n, k);
    13         return result;
    14     }
    15     
    16     public void generate(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> com,
    17             int depth, int n, int k){
    18                 if(com.size() == k){
    19                     ArrayList<Integer> tmp = new ArrayList<Integer>();
    20                     tmp.addAll(com);
    21                     result.add(tmp);
    22                     return;
    23                 }
    24                 
    25                 for(int i = depth; i <= n; i++){
    26                     com.add(i);
    27                     generate(result, com, i + 1, n, k);
    28                     com.remove(com.size() - 1);
    29                 }
    30                 
    31             }
    32 }
  • 相关阅读:
    E
    C. Connect Three(构造)
    判断矩形相交的方法
    字典树&&01字典树专题&&对字典树的理解
    J
    kmp专题
    Python 字典 popitem() 方法
    Python 字典 pop() 方法
    Python 字典(Dictionary) values()方法
    Python 字典(Dictionary) update()方法
  • 原文地址:https://www.cnblogs.com/feiling/p/3266343.html
Copyright © 2011-2022 走看看