[leetcode] 题型整理之排列组合

一般用dfs来做

最简单的一种:

17. Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
无需多言,只是说明一下这样初始化数组也是可以的:
private static char[][] chars = {{}, {}, {'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}, {'j', 'k', 'l'}, {'m', 'n', 'o'}, {'p','q', 'r', 's'}, {'t', 'u', 'v'}, {'w','x','y','z'}};

39. Combination Sum

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

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is: 

[
  [7],
  [2, 2, 3]
]

40. Combination Sum II

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.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
A solution set is: 

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

多了不可重复的要求,但是输入的数字不是unique的,因此要处理输出unique的情况。

处理的方法是如果有几个相同的数字,就只挑选其中第一个进入下一次dfs调用

注意两题都要先排序

start++;
while (start < size && candidates[start] == x) {
    start++;
}
if (start >= size) {
    break;
}
x = candidates[start];

46. Permutations

Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

47. Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

注意两题都要储存每一个数字是否被用到过。第一题不用先排序第二题要先排序。

第二题的关键是判断某一个数是不是第一次出现,如果不是,第一次出现时是否已经被加进来。如果已经加进来就不用再dfs调用这种情况了。

 //if the number appears more than once and the same number before it has not been used
if (i != 0 && nums[i] == nums[i - 1] && !flags[i - 1]) {
    continue;
}

60. Permutation Sequence

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

    1. "123"
    2. "132"
    3. "213"
    4. "231"
    5. "312"
    6. "321"

有点像数学题

适合用char[] 来储存初步结果,最后转换成string

要小心除零错

if (i != n -  1) {
    factorial /= (n - 1 - i);
}

 78. Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

和前面的combination差不多,但是subset每次调用helper函数的时候,都要先把candidate放入结果集中。

第二题的时候,需要先排序,同时用boolean数组保存是否被用到过。

31. Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

这像一道数学题,解题过程见水中的鱼[LeetCode] Next Permutation 解题报告

77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

跟之前的combination几乎一样。

79. Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

其实和一维的combination差不多。

18. 4Sum

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.

For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

 

其实这也可以算作排列组合吧,要考虑array当中有重复数字的情况,
处理重复的方法:
for (int i = 0; i < length; i++) {
  int x1 = nums[i];
  if (i != 0 && x1 == nums[i - 1]) {
    continue;
  }
  for (int j = i + 1; j < length; j++) {
    int x2 = nums[j];     if (j != 0 && i != j - 1 && x2 == nums[j - 1]) {       continue;     } ...
    

    do {
      end--;
    } while (start < end && nums[end] == b);

    do {
      start++;
    } while (start < end && nums[start] == a);


  }
}

 254. Factor Combinations

Numbers can be regarded as product of its factors. For example,

8 = 2 x 2 x 2;
  = 2 x 4.

Write a function that takes an integer n and return all possible combinations of its factors.

Note: 

  1. You may assume that n is always positive.
  2. Factors should be greater than 1 and less than n.

 

Examples: 
input: 1
output: 

[]
input:  37
output: 
[]
input:  12
output:
[
  [2, 6],
  [2, 2, 3],
  [3, 4]
]
input:  32
output:
[
  [2, 16],
  [2, 2, 8],
  [2, 2, 2, 4],
  [2, 2, 2, 2, 2],
  [2, 4, 4],
  [4, 8]
]

 

 

public class Solution {
    public List> getFactors(int n) {
        List> result = new ArrayList>();
        List rList = new ArrayList();
        if (n < 2) {
            return result;
        }
        helper(n, 2, rList, result);
        //System.out.println(result.toString());
        return result;
    }
    private void helper(int n, int start, List rList, List> result) {
        int size = rList.size();
        int limit = (int)(Math.floor(Math.sqrt(n)));
        boolean flag = false;
        for (int i = start; i <= limit; i++) {
            if (n % i == 0) {
                flag = true;
                rList.add(i);
                helper(n / i, i, rList, result);
                rList.remove(size);
            }
        }
        List newList = new ArrayList(rList);
        if (!rList.isEmpty()) {
            newList.add(n);
            result.add(newList);
        }
    }
}

 

转载于:https://www.cnblogs.com/Gryffin/p/6228740.html

你可能感兴趣的:([leetcode] 题型整理之排列组合)