Extremely simple recursive Java solution


  • 1
    L
    public class Solution {
        public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> finallist= new ArrayList<>();
            helper(n,1,k,finallist,new ArrayList<>());
            return finallist;
        }
        
        private void helper(int n,int j, int k, List<List<Integer>> finallist, List<Integer> list) {
            if(list.size()==k) {
                finallist.add(new ArrayList<>(list));
                return;
            }
            
            for(int i=j;i<=n;i++) {
                list.add(i);
                helper(n,i+1,k,finallist,list);
                list.remove(list.size()-1);
            }
            
        }
        
    }
    

Log in to reply
 

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