• 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],
    ]
    Solution:
    采用位运算来做,但是这样时间复杂度很高O(n* 2^ n)。
     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         for(int i = 0; i < Math.pow(2,n); i ++){
     7             ArrayList<Integer> row = new ArrayList<Integer>();
     8             for(int j = 0; j < n; j ++){
     9                 if((i >> j & 1)  == 1){
    10                     row.add(j + 1);
    11                 } 
    12             }
    13             if(row.size() == k)
    14                 result.add(row);
    15         }
    16         return result;
    17     }
    18 }

     第二遍: 使用递归。过不了大循环。

     1 public class Solution {
     2     ArrayList<ArrayList<Integer>> result = null;
     3     public ArrayList<ArrayList<Integer>> combine(int n, int k) {
     4         // Start typing your Java solution below
     5         // DO NOT write main() function
     6         result = new ArrayList<ArrayList<Integer>>();
     7         boolean[] map = new boolean[n];
     8         getAnswer(map, new ArrayList<Integer>(), k);
     9         return result;
    10     }
    11     public void getAnswer(boolean[] map, ArrayList<Integer> row, int n){
    12         if(n == 0) result.add(row);
    13         for(int i = 0; i < map.length; i ++){
    14             if(!map[i]){
    15                 map[i] = true;
    16                 row.add(i + 1);
    17                 getAnswer(map, row, n - 1);
    18                 map[i] = false;
    19             }
    20         }
    21     }
    22 }
  • 相关阅读:
    理解session
    java ee后台运行原理(Servlet)
    XML:是什么?怎样工作的?可以做什么?将来的发展有会怎样?
    互联网应用与企业级应用的区别
    自我介绍
    补充第一周
    第一周代码(四则运算)
    自我介绍
    程序1:自动生成小学四则运算题目
    初读《构建之法现代软件工程》的5个疑问
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3348482.html
Copyright © 2020-2023  润新知