代码随想录算法训练营第二十五天| 216. 组合总和 III 17.电话号码的字母组合

216. 组合总和 III 

    ​
    public  List> combinationSum3(int k, int n) {
        List> res = new ArrayList<>();
        Set path = new HashSet<>();
        countNum(k, n, path, res);
        List> result = new ArrayList<>();
        for (Set re : res) {
            result.add(re.stream().collect(Collectors.toList()));
        }
        return result;
//        HashSet> lists = new HashSet<>(result);
//        return lists.stream().collect(Collectors.toList());


    }

    public  void countNum(int k, int n, Set path, List> res) {
        if (path.size() > k || sumNum(path) > n) {
            return;
        }
        if (path.size() == k && sumNum(path) == n&&!res.contains(path)) {
            res.add(new HashSet<>(path));
            return;
        }
        for (int i = 1; i < 10; i++) {
            if (!path.contains(i)) {
                path.add(i);
                countNum(k, n, path, res);
                path.remove(i);
            }

        }
    }

    public  int sumNum(Set path) {
        int sum = 0;
        for (Integer integer : path) {
            sum += integer;
        }
        return sum;

    }

17. 电话号码的字母组合

public List letterCombinations(String A) {
    if (A == null || A.length() == 0) {
        return new ArrayList<>();
    }

    StringBuffer box = new StringBuffer();
    List ans = new ArrayList<>();
    backtrace(A, 0, box, ans);
    return ans;
}

final String[] ds = new String[] {
        "","",
        "abc",
        "def",
        "ghi",
        "jkl",
        "mno",
        "pqrs",
        "tuv",
        "wxyz"
};

void backtrace(String A, int i, StringBuffer box, List ans) {
    final int N = A == null ? 0 : A.length();
    // 如果我们发现状态满足要求
    if (box.length() == N) {
        ans.add(box.toString());
    }
    // 如果发现越界,第N个人开始就没有宝石选项了
    if (i >= N) {
        return;
    }
    // 遍历第i个人可以选择的宝石
    final int stonelndex = (int) (A.charAt(i) - '0');
    for (int idx = 0; idx < ds[stonelndex].length(); idx++) {
        // 拿到宝石
        Character stone = ds[stonelndex].charAt(idx);
        // /放到箱子中
        box.append(stone);
        backtrace(A, i + 1, box, ans);
        // 把自己的宝石拿出来,然后保持箱子原样!
        box.deleteCharAt(box.length() - 1);
    }
}

你可能感兴趣的:(算法,windows)