DFS排列组合问题
这四个使用DFS来求解所有组合和排列的例子很有代表性,这里做一个总结:
1.不带重复元素的子集问题
public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
// write your code here
ArrayList<ArrayList<Integer>> results = new ArrayList<>();
if (nums == null || nums.length == 0) {
return results;
}
Arrays.sort(nums);
DFS(results, new ArrayList<Integer>(), nums, 0);
return results;
}
public void DFS(ArrayList<ArrayList<Integer>> results, ArrayList<Integer> cur,
int[] nums, int start) {
results.add(new ArrayList<Integer>(cur));
for (int i = start; i < nums.length; i++) {
cur.add(nums[i]);
DFS(results, cur, nums, i+1);
cur.remove(cur.size()-1);
}
}
2.带重复元素的子集问题
public ArrayList<ArrayList<Integer>> subsetsWithDup(ArrayList<Integer> S) {
// write your code here
ArrayList<ArrayList<Integer>> results = new ArrayList<>();
if (S == null || S.size() == 0) {
return results;
}
Collections.sort(S);
DFS(results, new ArrayList<Integer>(), S, 0);
return results;
}
public void DFS(ArrayList<ArrayList<Integer>> results,
ArrayList<Integer> cur,
ArrayList<Integer> S,
int start) {
results.add(new ArrayList<>(cur));
for (int i = start; i < S.size(); i++) {
if(i != start && S.get(i) == S.get(i - 1)) {
continue;
}
cur.add(S.get(i));
DFS(results, cur, S, i+1);
cur.remove(cur.size()-1);
}
}
3.不带重复元素的全排列问题
public List<List<Integer>> permute(int[] nums) {
// write your code here
List<List<Integer>> results = new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0) {
results.add(new ArrayList<Integer>());
return results;
}
boolean[] used = new boolean[nums.length];
DFS(results, new ArrayList<Integer>(), nums, used);
return results;
}
public void DFS(List<List<Integer>> results, List<Integer> cur, int[] nums, boolean[] used) {
if (cur.size() == nums.length) {
results.add(new ArrayList<Integer>(cur));
return;
}
for(int i = 0; i<nums.length; i++) {
if (used[i]) {
continue;
}
used[i] =true;
cur.add(nums[i]);
DFS(results, cur, nums, used);
used[i] =false;
cur.remove(cur.size()-1);
}
}
4.带重负元素的全排列问题
public List<List<Integer>> permuteUnique(int[] nums) {
// Write your code here
List<List<Integer>> results = new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0) {
results.add(new ArrayList<Integer>());
return results;
}
Arrays.sort(nums);
boolean[] used = new boolean[nums.length];
DFS(results, new ArrayList<Integer>(), used, nums);
return results;
}
public void DFS(List<List<Integer>> results, List<Integer> cur, boolean[] used, int[] nums) {
if (cur.size() == nums.length) {
results.add(new ArrayList<Integer>(cur));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
if (i > 0 && nums[i] == nums[i - 1] && !used[i-1]) {
continue;
}
used[i] = true;
cur.add(nums[i]);
DFS(results, cur, used, nums);
used[i] = false;
cur.remove(cur.size() -1);
}
}
寻找丢失的数 II*
给一个由 1 - n 的整数随机组成的一个字符串序列,其中丢失了一个整数,请找到它。
回溯,当前位置可以单独,也可以和下一个结合,当前为0一定不行。curIndex控制啥时候结束。
public int findMissing2(int n, String str) {
// Write your code here
if (n < 1 || str == null) {
return 0;
}
char[] chars = str.toCharArray();
boolean[] appeared = new boolean[n + 1];
int[] curIndex = {0};
help(appeared, chars, curIndex, n);
for (int i = 1; i < appeared.length; i++) {
if (!appeared[i]) {
return i;
}
}
return -1;
}
public void help(boolean[] appeared, char[] chars, int[] curIndex, int n) {
if (curIndex[0] >= chars.length) {
return;
}
if (chars[curIndex[0]] == '0') {
return;
}
if (!appeared[chars[curIndex[0]] - '0']) {
appeared[chars[curIndex[0]] - '0'] = true;
curIndex[0]++;
help(appeared, chars, curIndex, n);
if (curIndex[0] >= chars.length) {
return;
}
curIndex[0]--;
appeared[chars[curIndex[0]] - '0'] = false;
}
if (curIndex[0] < chars.length - 1) {
int c1 = chars[curIndex[0]] - '0';
int c2 = chars[curIndex[0] + 1] - '0';
int newnum = c1 * 10 + c2;
if (newnum <= n && !appeared[newnum]) {
appeared[newnum] = true;
curIndex[0] += 2;
help(appeared, chars, curIndex, n);
if (curIndex[0] >= chars.length) {
return;
}
curIndex[0]-=2;
appeared[newnum] = false;
}
}
}
DFS排列组合问题的更多相关文章
- Codeforces 991E. Bus Number (DFS+排列组合)
解题思路 将每个数字出现的次数存在一个数组num[]中(与顺序无关). 将出现过的数字i从1到num[i]遍历.(i from 0 to 9) 得到要使用的数字次数数组a[]. 对于每一种a使用排列组 ...
- dfs 排列组合——找所有子集(重复元素和不重复元素)
17. 子集 中文 English 给定一个含不同整数的集合,返回其所有的子集. 样例 样例 1: 输入:[0] 输出: [ [], [0] ] 样例 2: 输入:[1,2,3] 输出: [ [3], ...
- DFS实现排列组合
所谓排列,是指从给定的元素序列中依次取出元素,需要考虑取出顺序.比如,取出元素3, 5,因取出顺序的不同,则形成的序列{3, 5}与{5, 3}是不同的排列序列.对于长度为n的元素序列取出k个元素,则 ...
- [leetcode] 题型整理之排列组合
一般用dfs来做 最简单的一种: 17. Letter Combinations of a Phone Number Given a digit string, return all possible ...
- Day4:T3搜索 T4数学题排列组合
T3:搜索 很出名的题吧,费解的开关 同T2一样也是一题很考思考的 附上题解再解释吧: 对于每个状态,算法只需要枚举第一行改变哪些灯的状态,只要第一行的状态固定了,接下来的状态改变方法都是唯一的:每一 ...
- 2017ACM暑期多校联合训练 - Team 1 1006 HDU 6038 Function (排列组合)
题目链接 Problem Description You are given a permutation a from 0 to n−1 and a permutation b from 0 to m ...
- LeetCode OJ:Combinations (排列组合)
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For exampl ...
- 学习sql中的排列组合,在园子里搜着看于是。。。
学习sql中的排列组合,在园子里搜着看,看到篇文章,于是自己(新手)用了最最原始的sql去写出来: --需求----B, C, F, M and S住在一座房子的不同楼层.--B 不住顶层.C 不住底 ...
- .NET平台开源项目速览(11)KwCombinatorics排列组合使用案例(1)
今年上半年,我在KwCombinatorics系列文章中,重点介绍了KwCombinatorics组件的使用情况,其实这个组件我5年前就开始用了,非常方便,麻雀虽小五脏俱全.所以一直非常喜欢,才写了几 ...
随机推荐
- cms-帖子管理
mapper: <?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC & ...
- LeetCode Rotate Array 翻转数组
题意:给定一个数组,将该数组的后k位移动到前n-k位之前.(本题在编程珠玑中第二章有讲) 思路: 方法一:将后K位用vector容器装起来,再移动前n-k位到后面,再将容器内k位插到前面. class ...
- CSS样式表优化
前几天公司要模仿一家客户的网站模板来为另一客户新建一个模板,说白了就是换个数据源,然后样式表再小修小改一下就行了.但通过浏览器控制台下载素材时,发现这个网站开发的挺专业的,单就样式表而言,代码工整,注 ...
- linux 命令——47 iostat (转)
Linux系统中的 iostat 是I/O statistics(输入/输出统计)的缩写,iostat工具将对系统的磁盘操作活动进行监视.它的特点是汇报磁盘活动统计情况,同时也会 汇报出CPU使用情况 ...
- 我的Linux学习之路的感悟
首先要跟大家说声抱歉,这么久一直没有更新,有负大家对我的期望. 半年的Linux运维的学习到目前已工作一个月零9天,这一路走来的艰辛和挣扎只有自己最清楚. 首先要感谢公司的同事的宽容接纳和耐心指点.感 ...
- python_78_软件目录结构规范
一定要看http://www.cnblogs.com/alex3714/articles/5765046.html #print(__file__)#打印的是文件的相对路径 import os pri ...
- python_62_装饰器5
import time def timer(func): #timer(test1) func=test1 def deco(*args,**kwargs): start_time=time.time ...
- Angular6中[ngClass]、[ngStyle]的基本使用
1.ngStyle 基本用法 <div [ngStyle]="{'background-color':'green'}"></<div> 判断添加 & ...
- response.setContentType("text/html;charset=utf-8")后依然乱码的解决方法
从浏览器获取数据到服务器,服务器将得到数据再显示在浏览器上英文字母正常显示,中文字符乱码的问题,已经使用了 response.setContentType("text/html;charse ...
- daemon函数实现原理 守护进程
linux提供了daemon函数用于创建守护进程,实现原理如下: #include <unistd.h> int daemon(int nochdir, int noclose); 1. ...