• 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);
    			}
    	}
    
  • 相关阅读:
    第五次团队作业
    第三次个人作业
    第一次编程作业
    自我介绍
    个人总结
    第三次个人作业
    第一次结对作业
    第二次作业
    第一次博客作业
    Alpha总结
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4513126.html
Copyright © 2020-2023  润新知