Concise and Clear Java Iterative Solution


  • 0
    M
    public List<List<Integer>> combine(int n, int k) {
    	List<List<Integer>> ans = new ArrayList();
    	ans.add(new ArrayList());
    	for (int level = 1; level <= k; level++) {
    		int size = ans.size();
    		for (int i = 0; i < size; i++) {
    			List<Integer> cur = ans.get(i);
    			for (int j = 1; j < n - (k - level); j++) {
    				if (cur.isEmpty() || cur.get(cur.size() - 1) < j) {
    					List<Integer> newcur = new ArrayList(cur);
    					newcur.add(j);
    					ans.add(newcur);
    				}
    			}
    			cur.add(n - (k - level));
    		}
    	}
    
    	return ans;
    
    }

Log in to reply
 

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