LeetCode 216. Combination Sum III

Combination Sum III

public class Solution {
    public IList<IList<int>> CombinationSum3(int k, int n) {
        List<int> visited = new List<int>();
        List<IList<int>> ret = new List<IList<int>>();
        Find(k, n, 1, 1, 0, visited, ret);
        return ret;
    }
    
    private void Find(int k, int n, int level, int s, int sum, List<int> visited, List<IList<int>> ret){
        if(level == k && s <= n && n <= 9) {
            List<int> r = new List<int>(visited);
            r.Add(n);
            ret.Add(r);
            return;
        } 
        if(level == k || s >= n) return;
        for(int i = s; i < 9; i++){
            visited.Add(i);
            Find(k, n-i, level+1, i+1, sum+i, visited, ret);
            visited.RemoveAt(visited.Count-1);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *