10-line C# iterative solution


  • 0
    H
    public class Solution {
        public IList<IList<int>> Combine(int n, int k) {
            var r = new List<IList<int>>();
            var p = new int[k];
            for (int i = 0; i < k; i++) p[i] = i + 1;
            while(true) {
                r.Add(p.ToList());
                int i = k - 1;
                while (i >= 0 && p[i] == n - k + i + 1) i--;
                if (i < 0) return r;
                var c = ++p[i];
                for (int j = i + 1; j < k; j++) p[j] = ++c; 
            }
        }
    }
    

    imagine if n = 5, k = 3, then it create an array (length = 3). where p[0] = 1, p[1] = 2, p[2] = 3.
    try to increment p[2], if not it increment p[1]...


Log in to reply
 

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