JAVA my iterative 13ms and recursive 7ms solutions


  • 3
    P

    iterative solution

    public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        List<Integer> kind = new ArrayList<Integer>();
        int i = 1;
        while(i<=n || kind.size()!=0){
            if(kind.size()==k){
                list.add(new ArrayList(kind));
            }
            if(i>n||kind.size()==k){
                i = kind.get(kind.size()-1)+1;
                kind.remove(kind.size()-1);
            }
            else{
                kind.add(i);
                i++;
            }
        }
        return list;
    }
    

    recursive solution

    public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        helper(list , new ArrayList<Integer>(),n,k,1);
        return list;
    }
    
    public void helper(List<List<Integer>> list,List<Integer> kind , int n , int k,int start){
        if(kind.size() == k){
            list.add(new ArrayList(kind));
            return;
        }
        
        for(int i = start;i<=n;i++){
            if(!kind.contains(i)){
                kind.add(i);
                helper(list,kind,n,k,i);
                kind.remove(kind.size()-1);
            }
        }
    }

Log in to reply
 

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