[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):
"123""132""213""231""312""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,23,2,1 → 1,2,31,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 a, b, c, 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]
]
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:
- You may assume that n is always positive.
- 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] 题型整理之排列组合的更多相关文章
- leetCode 47.Permutations II (排列组合II) 解题思路和方法
Permutations II Given a collection of numbers that might contain duplicates, return all possible un ...
- [leetcode] 题型整理之二叉树
94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' va ...
- [leetcode] 题型整理之动态规划
动态规划属于技巧性比较强的题目,如果看到过原题的话,对解题很有帮助 55. Jump Game Given an array of non-negative integers, you are ini ...
- [leetcode] 题型整理之数字加减乘除乘方开根号组合数计算取余
需要注意overflow,特别是Integer.MIN_VALUE这个数字. 需要掌握二分法. 不用除法的除法,分而治之的乘方 2. Add Two Numbers You are given two ...
- [leetcode] 题型整理之cycle
找到环的起点. 一快一慢相遇初,从头再走再相逢.
- [leetcode]题型整理之用bit统计个数
137. Single Number II Given an array of integers, every element appears three times except for one. ...
- [leetcode] 题型整理之图论
图论的常见题目有两类,一类是求两点间最短距离,另一类是拓扑排序,两种写起来都很烦. 求最短路径: 127. Word Ladder Given two words (beginWord and end ...
- [leetcode] 题型整理之查找
1. 普通的二分法查找查找等于target的数字 2. 还可以查找小于target的数字中最小的数字和大于target的数字中最大的数字 由于新的查找结果总是比旧的查找结果更接近于target,因此只 ...
- [leetcode] 题型整理之排序
75. Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects ...
随机推荐
- loadrunner关联取参--响应值unicode编码处理过
背景:做电商提交订单,需要获取订单号,然后进行支付.状态变更等操作 submitOrder() { lr_think_time(); /* 提交订单 */ /* specsId:规格ID,hyh_go ...
- System类和Random类
System类 成员方法: public static void gc():运行垃圾回收器 public static void exit(int status):退出垃圾回收器 public sta ...
- php操作mongodb
<?php set_time_limit(0); $mongo = new Mongo('192.168.33.50:27017'); //连接远程主机22011端口 $db = $mongo- ...
- python描述符(descriptor)、属性(property)、函数(类)装饰器(decorator )原理实例详解
1.前言 Python的描述符是接触到Python核心编程中一个比较难以理解的内容,自己在学习的过程中也遇到过很多的疑惑,通过google和阅读源码,现将自己的理解和心得记录下来,也为正在为了该问题 ...
- js只弹窗一次
<script> var alertmessage="检测到您当前浏览器为IE8或以下版本,建议您使用IE9或以上版本,或者火狐.谷歌浏览器,才能体验到最佳效果" fu ...
- 直接拿来用,最火的.NET开源项目
综合类 微软企业库 微软官方出品,是为了协助开发商解决企业级应用开发过程中所面临的一系列共性的问题, 如安全(Security).日志(Logging).数据访问(Data Access).配置管理( ...
- [Head First设计模式]生活中学设计模式——迭代器模式
系列文章 [Head First设计模式]山西面馆中的设计模式——装饰者模式 [Head First设计模式]山西面馆中的设计模式——观察者模式 [Head First设计模式]山西面馆中的设计模式— ...
- cpu对各种运算的速度对比
今天忽然想到cpu对各种基本运算的速度对比,我对比了异或,加法和乘法,结果发现速度时间,加法小于乘法小于异或, 原本我以为异或会是最快的,结果异或是最慢的,这跟cpu中的alu算术逻辑单元的实现有关, ...
- JavaScript正则表达式详解(二)JavaScript中正则表达式函数详解
二.JavaScript中正则表达式函数详解(exec, test, match, replace, search, split) 1.使用正则表达式的方法去匹配查找字符串 1.1. exec方法详解 ...
- pathinfo()、dirname()、basename()获得文件的路径,名称等信息说明
在PHP中,若想通过函数获得一个文件的路径.名称,或者是扩展名等,是非常容易的一件事.可以使用dirname().basename().pathinfo()等多种途径获得相应的信息. 假设现在有一个图 ...