Can anyone help with this? What's the difference between Python version and Java version?


  • 0
    M

    Can anyone help with this? What's the difference between Python version and Java version?

    Python version (doesn't work)

    def comb(can, target):
        
        res, sol = [], []
        helper(can, 0 ,res, sol, target)
        return res
        
    def helper(array, index, res, sol, target):
        if target == 0:
            res.append(list(sol))
            return
        for i in range(index, len(array)):
            if array[i] > target:
                return
            sol.append(array[i])
            helper(array, i+1, res, sol, target - array[i])
            sol.pop()
            while i + 1  <len(array) and array[i+1] ==array[i]:
                i = i + 1
            
    print comb([1,1,1], 2)
    

    Java Version (correct)

    class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        	List<List<Integer>> res = new ArrayList<List<Integer>>();
        	List<Integer> sol = new ArrayList<Integer>();
        	this.helper(candidates, 0, res, sol, target);
        	return res;
        }
        
        private void helper(int[] array, int index, List<List<Integer>> res, List<Integer> sol, int target) {
        	if (target == 0) {
        		res.add(new ArrayList<Integer>(sol));
        		return;
        	}
        	for (int i = index; i<array.length; i ++) {
        		if (array[i] > target) {
        			return;
        		}
        		sol.add(array[i]);
        		this.helper(array, i + 1, res, sol, target - array[i]);
        		sol.remove(sol.size() - 1);
        		while (i + 1 < array.length && array[i + 1] == array[i]) {
        			i++;
        		}
        	}
        } 
    }
    

  • 0
    M
    This post is deleted!

Log in to reply
 

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