Minimal Java Solution - Can be modified for other Combination Problems 1 and 3


  • 1
    J
    public class Solution {
        public List<List<Integer>> combinationSum2(int[] c, int n) {
            List<List<Integer>> L = new ArrayList();
            Arrays.sort(c);
            ctl(n, 0, c, new ArrayList<Integer>(), L);
            return(L);
        }
        
        public void ctl(int n, int begin, int[] c, List<Integer> l, List<List<Integer>> L){
            if(n <= 0){
                if(n == 0){
                    List<Integer> li = new ArrayList<Integer>(l);
                    L.add(li);
                }
                return;
            }
        
            for(int i = begin; i < c.length && n - c[i] >= 0;i++){
                if(i > begin && c[i] == c[i - 1])
                    continue;
                l.add(c[i]);
                ctl(n - c[i], i + 1, c, l, L);
                l.remove(l.size() - 1);
            }
            
            return;
        }
    }

Log in to reply
 

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