Java simple iterative solution


  • 0
    P
    public class Solution {
        public List<List<Integer>> combine(int n, int k) {
            LinkedList<List<Integer>> ans = new LinkedList<>();
            List<Integer> t = new ArrayList<>();
            ans.add(t);
            for (int i = 0; i < k; i++) {
                int sum = ans.size();
                for (; sum > 0; sum--) {
                    t = ans.pollFirst();
                    int l = i > 0 ? t.get(t.size()-1):0;
                    for (int j = l+1; j <= n-k+1+i; j++) {
                        List<Integer> temp = new ArrayList<>(t);
                        temp.add(j);
                        ans.add(temp);
                    }
                }
            }
            return ans;
        }
    }

Log in to reply
 

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