Simple java solution using backtracking


  • 1
    S
    public class Solution {
        private List<List<Integer>> result = new ArrayList<List<Integer>>();
        private int max;
        public List<List<Integer>> combine(int n, int k) {
            max = n;
            generator(0, k, new ArrayList<Integer>());
            return result;
        }
        private void generator(int bigest, int count, List<Integer> list){
            if(count == 0)
                result.add(list);
            else{
                for(int i = bigest + 1; i <= max - count + 1; ++i){
                    List<Integer> temp = new ArrayList<Integer>(list);
                    temp.add(i);
                    generator(i, count - 1, temp);
                }
            }
        }
    }

Log in to reply
 

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