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],
    ]
    public class Solution {
        public ArrayList<ArrayList<Integer>> combine(int n, int k) {
            if(k>n)
                return null;
            ArrayList<Integer> ai = new ArrayList<Integer>();
            ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>();
            for(int m=0;m<n;m++){
                ai=new ArrayList<Integer>();
                ai.add(m+1);
                re.add(ai);
            }
            for(int i=1;i<k;i++){
                Iterator<ArrayList<Integer>> it = re.iterator();
                ArrayList<ArrayList<Integer>> tempre = new ArrayList<ArrayList<Integer>>();
                while(it.hasNext()){
                    ArrayList<Integer> temp = it.next();
                    int tt = temp.get(temp.size()-1);
                    for(int j=tt+1;j<=n;j++){
                        ArrayList<Integer> newtemp = new ArrayList<Integer>();
                        newtemp.addAll(temp);
                        
                        newtemp.add(j);
                        tempre.add(newtemp);
                    }
                }
                re=tempre;
            }
            return re;
            
        }
    }
  • 相关阅读:
    FreeBSD10下的MySQL5.5配置安装
    TCP Wrappers
    SNAT技术
    子网掩码, 网段主机数计算
    functools wraps
    数据库引擎
    restframework
    Python使用asyncio+aiohttp异步爬取猫眼电影专业版
    Linux 总结
    Nginx日志管理
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3721944.html
Copyright © 2011-2022 走看看