zoukankan      html  css  js  c++  java
  • 77. Combinations (JAVA)

    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],
    ]

    带回溯的递归。(带回溯没法用循环实现)

    class Solution {
        public List<List<Integer>> combine(int n, int k) {
            result = new ArrayList<>();
            List<Integer> ans = new ArrayList<Integer>();
            dfs(ans,n,k,1);
            return result;
        }
        
        void dfs(List<Integer> ans, int n, int k, int depth){
            if(ans.size()==k) {
                List<Integer> new_ans = new ArrayList<Integer>(ans);
                result.add(new_ans);
                return;
            }
            if(depth>n){
                return;
            }
            
            ans.add(depth);
            dfs(ans,n,k,depth+1);
            ans.remove(ans.size()-1);
            dfs(ans,n,k,depth+1);
            
        }
        
        private List<List<Integer>> result;
    }
  • 相关阅读:
    Sql server数据库设计 7
    day08作业
    day01作业
    day07作业.
    day05作业
    day04作业
    day02作业
    初学Java的一些注意事项
    day07作业
    Week03面向对象入门
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10929529.html
Copyright © 2011-2022 走看看