zoukankan      html  css  js  c++  java
  • Java for LeetCode 077 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],
    ]
    
    解题思路:
    DFS,JAVA实现如下:
    	public static void main(String args[]) {
    		List<List<Integer>> list = combine(5, 2);
    		System.out.println(list.size());
    		for (List<Integer> alist : list)
    			System.out.println(alist + "*");
    	}
    
    	static public List<List<Integer>> combine(int n, int k) {
    		List<List<Integer>> list = new ArrayList<List<Integer>>();
    		if (n <= 0 || k > n)
    			return list;
    		dfs(list, n, k, 0);
    		return list;
    	}
    
    	static List<Integer> alist = new ArrayList<Integer>();
    
    	static void dfs(List<List<Integer>> list, int n, int k, int depth) {
    		if (depth >= k) {
    			list.add(new ArrayList<Integer>(alist));
    			return;
    		}
    		if (depth == 0)
    			for (int i = 1; i <= n - k + 1; i++) {
    				alist.add(i);
    				dfs(list, n, k, depth + 1);
    				alist.remove(alist.size() - 1);
    			}
    		else
    			for (int i = 1; i <= n - alist.get(alist.size() - 1) + k - depth - 1; i++) {
    				alist.add(alist.get(alist.size() - 1) + i);
    				dfs(list, n, k, depth + 1);
    				alist.remove(alist.size() - 1);
    			}
    	}
    
  • 相关阅读:
    剑指Offer--反转链表
    剑指Offer--链表中倒数第k个结点
    面向对象的六原则一法则
    常见错误汇总
    记人生第一次CF体验
    Game of Credit Cards
    Shell Game (模拟)
    数列分块入门 1 LibreOJ
    范德蒙恒等式
    C. Vasya and String (尺取法)
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4513126.html
Copyright © 2011-2022 走看看