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);
    			}
    	}
    
  • 相关阅读:
    [HDU]1086You can Solve a Geometry Problem too
    [HDU]2161Primes
    [HDU]2098分拆素数和
    [HDU]1431素数回文
    [HDU]1527取石子游戏
    [HDU]2092整数解
    [HDU]1405The Last Practice
    [HDU]2565放大的X
    [HDU]1723Distribute Message
    [HDU]1208Pascal's Travels
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4513126.html
Copyright © 2011-2022 走看看