一般用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<List<Integer>> getFactors(int n) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> rList = new ArrayList<Integer>();
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<Integer> rList, List<List<Integer>> 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<Integer> newList = new ArrayList<Integer>(rList);
if (!rList.isEmpty()) {
newList.add(n);
result.add(newList);
}
}
}

[leetcode] 题型整理之排列组合的更多相关文章

  1. leetCode 47.Permutations II (排列组合II) 解题思路和方法

    Permutations II  Given a collection of numbers that might contain duplicates, return all possible un ...

  2. [leetcode] 题型整理之二叉树

    94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' va ...

  3. [leetcode] 题型整理之动态规划

    动态规划属于技巧性比较强的题目,如果看到过原题的话,对解题很有帮助 55. Jump Game Given an array of non-negative integers, you are ini ...

  4. [leetcode] 题型整理之数字加减乘除乘方开根号组合数计算取余

    需要注意overflow,特别是Integer.MIN_VALUE这个数字. 需要掌握二分法. 不用除法的除法,分而治之的乘方 2. Add Two Numbers You are given two ...

  5. [leetcode] 题型整理之cycle

    找到环的起点. 一快一慢相遇初,从头再走再相逢.

  6. [leetcode]题型整理之用bit统计个数

    137. Single Number II Given an array of integers, every element appears three times except for one. ...

  7. [leetcode] 题型整理之图论

    图论的常见题目有两类,一类是求两点间最短距离,另一类是拓扑排序,两种写起来都很烦. 求最短路径: 127. Word Ladder Given two words (beginWord and end ...

  8. [leetcode] 题型整理之查找

    1. 普通的二分法查找查找等于target的数字 2. 还可以查找小于target的数字中最小的数字和大于target的数字中最大的数字 由于新的查找结果总是比旧的查找结果更接近于target,因此只 ...

  9. [leetcode] 题型整理之排序

    75. Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects ...

随机推荐

  1. 菜鸟的Python学习之路(流水账)

    揭开Python的面纱 开始是因为别人说Python简单才开始学的,然后那段时间刚考完研,也没什么事,就多少瞅了瞅,然后发现语法的确简单很多,或者说简洁更合适. 当时看的是简明Python教程,没用多 ...

  2. <<< java环境搭建

    先百度搜索"jdk下载"            安装完成之后,到系统环境变量设置(电脑右键,属性,高级系统设置) 然后点击下面path系统变量,把C:\Program Files ...

  3. ionic ios发布图标启动也不能正确加载问题

    前两天发布ios的时候发现ios安装的图标和启动页的时候不能正确显示,重新发布也不能正确显示,修改方法 在ionic build ios --release之前执行ionic resources即可

  4. JavaScript中ActiveXObject对象

    JavaScript中ActiveXObject对象是启用并返回 Automation 对象的引用.使用方法: newObj = new ActiveXObject( servername.typen ...

  5. JVM内存模型、指令重排、内存屏障概念解析

    在高并发模型中,无是面对物理机SMP系统模型,还是面对像JVM的虚拟机多线程并发内存模型,指令重排(编译器.运行时)和内存屏障都是非常重要的概念,因此,搞清楚这些概念和原理很重要.否则,你很难搞清楚哪 ...

  6. 谷歌地图地理解析和反解析geocode.geocoder详解

    地址解析就是将地址(如:贵州省贵阳市)转换为地理坐标(如经度:106.71,纬度:26.57)的过程. 地理反解析和上面的过程相反是将地理坐标(如纬度:26.57,经度:106.71)转换为地址(中国 ...

  7. tyvj1106 登山

    背景     在很久很久以前,有一个动物村庄,那里是猪的乐园(^_^),村民们勤劳.勇敢.善良.团结……    不过有一天,最小的小小猪生病了,而这种病是极其罕见的,因此大家都没有储存这种药物.所以晴 ...

  8. UIScrollView无法滚动的解决办法

    如果UIScrollView无法滚动,可能是以下原因: 没有设置contentSize scrollEnabled = NO 没有接收到触摸事件:userInteractionEnabled = NO ...

  9. Mac Pro 利用PHP导出SVN新增或修改过的文件

    先前在 Windows 操作系统下,习惯用 TortoiseSVN 导出新增或修改过的文件([相当实用]如何让TortoiseSVN导出新增或修改过的文件 ),最近换成了 Mac Pro 笔记本电脑, ...

  10. PHP常量详解:define和const的区别

    常量是一个简单值的标识符(名字).如同其名称所暗示的,在脚本执行期间该值不能改变(除了所谓的魔术常量,它们其实不是常量).常量默认为大小写敏感.通常常量标识符总是大写的. 可以用 define() 函 ...