lintcode153- Combination Sum II- medium

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

 Notice
  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.
Example

Given candidate set [10,1,6,7,2,1,5] and target 8,

A solution set is:

[
  [1,7],
  [1,2,5],
  [2,6],
  [1,1,6]
]

和 I 差不多,本题区别在答案序列内能出现“同种不同个”的数字,但答案序列间不能出现同时使用“同种不同个”的数字。比如 [10,1a,6,7,2,1b,5] and target 8,不允许产生[1a 7] [1b 7],但需要产生[1a 1b 6]

DFS。先排序,(这题不用去重,因为需要允许重复用一“种”数字)。递归函数里for循环试着轮流加入某个数字后的数字,继续递归,再删去复原。继续递归的时候要限制  1.下一层只能用再后一位的数字(同一“种”数字下一层还能加) 2.这个for循环内如果前面加过这“种”数字了,就不可以再试着递归了。

2.避免了产生[1a 7] [1b 7]这种,1.避免了产生[1a 1a 1a 1a 1a 1a 1b]这种,保证了可以产生产生[1a 1b 6]这种(下一个循环又可以加同种不同个了)

题型总结:有几种不同等级的unique要求

1. 避免[1a 7] [1b 7]。同种不同个各自出现的重复

2.保留[1a 1b 7]这种按顺序出现同种不同个的,数字重复但答案不重复的情况

3.避免[1a 1b] [1b 1a] 同种不同个在答案内部顺序打乱的重复

subsets II 和 combination sum II 因为DFS实现天然保证了顺序,不用担心3。要注意1,2。

permutation II 已经默认所有数字都要出现了,不用担心1,2。要注意3

subsets II:http://www.cnblogs.com/jasminemzy/p/7566562.html

permutation II:http://www.cnblogs.com/jasminemzy/p/7568360.html

combination sum II:http://www.cnblogs.com/jasminemzy/p/7771736.html

public class Solution {
    /*
     * @param num: Given the candidate numbers
     * @param target: Given the target number
     * @return: All the combinations that sum to target
     */
    public List<List<Integer>> combinationSum2(int[] num, int target) {
        // write your code here
        List<List<Integer>> result = new ArrayList<>();
        if (num == null || num.length == 0) {
            return result;
        }
        Arrays.sort(num);
        dfs(num, target, 0, new ArrayList<Integer>(), result);
        return result;
    }
    
    private void dfs(int[] num, int targetDist, int idx, List<Integer> crt, List<List<Integer>> result) {
        if (targetDist < 0) {
            return;
        }
        if (targetDist == 0) {
            result.add(new ArrayList<Integer>(crt));
        }
        for (int i = idx; i < num.length; i++) {
            // !!这里有一个非常subtle的去重
            // 既要保证同一种数字可以被加入多次  [1a 1b 6 7 8] -> [1a 1b 6]
            // 又要保证同一种数字不可以作为同一个作用在不同组里出现 -×-> [1a 7] [1b 7]
            if (i > idx && num[i] == num[i - 1]) {
                continue;
            }
            crt.add(num[i]);
            dfs(num, targetDist - num[i], i + 1, crt, result);
            crt.remove(crt.size() - 1);
        }
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/7771736.html