40. Combination Sum II

比较典型的排列组合bakctrack.

public class Solution {
    public List<List<Integer>> combinationSum2(int[] nums, int target) 
    {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        
        if(nums.length == 0) return res;
        
        Arrays.sort(nums);
        
        helper(res,nums,new ArrayList<Integer>(),target,0);
        
        return res;
    }
    
    public void helper(List<List<Integer>> res, int[] nums, List<Integer> tempList, int target, int m)
    {
        if(target == 0)
        {
            res.add(tempList);
            return ;
        }
        else
        {
            for(int i = m ; i < nums.length;i++)
            {
                if(i != m && nums[i] == nums[i-1]) continue;
                if(target - nums[i] < 0) break;
                
                tempList.add(nums[i]);
                helper(res,nums,new ArrayList<>(tempList),target - nums[i],i+1);
                tempList.remove(tempList.size()-1);
                
            }
        }
    }
}

没啥可说的。。

试一下SWAP的方式。

试个P啊。。那个是permutation..这个不是。。



三刷。

一样的,不能重复用元素了而已。。

Time: O() 和上一个一样,不会算。。只知道还是指数级别的。。
Space: O(n)

public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (candidates.length == 0) return res;
        Arrays.sort(candidates);
        dfs(res, candidates, target, 0, new ArrayList<>());
        return res;
    }
    public void dfs(List<List<Integer>> res, int[] nums, int target, int m, List<Integer> tempList) {
        if (target == 0) {
            res.add(tempList);
            return;
        } else {
            for (int i = m; i < nums.length; i++) {
                if (target - nums[i] < 0) break;
                if (i != m && nums[i] == nums[i-1]) continue;
                tempList.add(nums[i]);
                dfs(res, nums, target - nums[i], i + 1, new ArrayList<>(tempList));
                tempList.remove(tempList.size()-1);
            }
            return;
        }
    }
}
posted @ 2016-11-08 05:41  哇呀呀..生气啦~  阅读(78)  评论(0)    收藏  举报