Accepted recursive solution in Java. Pretty straight forward. No complex index manipulation


  • 2
    V

    This recursive solution is according to the math equation: enter image description here
    Base conditions: k == 1 and k == n, easy to do. The tricky part is in recursively calling combine(n - 1, k - 1), each time you need add n into each list. Let me know if you have better suggestions.

    public class Solution {
        public List<List<Integer>> combine(int n, int k) {
            if(k > n || k < 0)
                return null;
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            
             if(k == 1){
                for(int i = 1; i <= n; i++){
                    List<Integer> inner = new ArrayList<Integer>();
                    inner.add(i);
                    result.add(inner);
                }
            }else if(k == n){
                List<Integer> inner = new ArrayList<Integer>();
                for(int i = 1; i <= n; i++)
                    inner.add(i);
                result.add(inner); 
            }else{
                for(List<Integer> sub : combine(n - 1, k - 1)){
                    List<Integer> temp = new ArrayList<Integer>(sub);
                    temp.add(n);
                    result.add(temp);
                }
                
                result.addAll(combine(n - 1, k));
            }
            
            return result;
        }
    }
    

  • 0
    V

    Math is pretty important for CS :p Actually CS originally is a branch of Math


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.