LeetCode解题报告—— Permutations & Permutations II & Rotate Image
1. 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]
]
思路;直接使用递归来遍历即可,因为数字是不重复的所以,所以这里的每层递归都从索引0开始遍历整个数组,将不在集合中的数字添加到集合中,到集合元素个数达到要求时返回到上层递归即可。
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
backtrack(list, new ArrayList<>(), nums);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
if(tempList.size() == nums.length){
list.add(new ArrayList<>(tempList));
} else{
for(int i = 0; i < nums.length; i++){
if(tempList.contains(nums[i])) continue; // element already exists, skip
tempList.add(nums[i]);
backtrack(list, tempList, nums);
tempList.remove(tempList.size() - 1); //注意这里remove方法是按照索引来删的,因为参数是int类型
}
}
}
2. 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]
]
思路:和上一题不同在于数组中可能含有重复数字。解法和上题类似,但是递归遍历数组时要考虑到的是因为数组中有重复数字,所以遇到相同数时要做判断,一是如果是用过的数字则不能再用,利用一个布尔数组来记录,还有一个避免对连着的重复数字循环遍历,以 1,1,2和1,1,1来举例,找所有的组合仍然是一层层从索引0到2循环遍历,总共有3层,所以对于 1,1来说第一层遍历到第二个1,第二层遍历到第一个1和第一层遍历到第一个1,第二层遍历到第二个1这两种情况是完全相同的,因此需要避免这种重复的情况,因此对元数组排序一遍后,对连着的重复数字只需要递归遍历一遍即可,如果当前数字和前面数字相同并且前面数字还没用过的情形则直接跳过。
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
backtrack(list, new ArrayList<>(), nums, new boolean[nums.length]);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, boolean [] used){
if(tempList.size() == nums.length){
list.add(new ArrayList<>(tempList));
} else{
for(int i = 0; i < nums.length; i++){
// 当nums[i]用过了或者nums[i]和前一个数字相等且前一个数字没用过的情形则直接跳过
if(used[i] || (i > 0 && nums[i] == nums[i-1] && !used[i - 1])) continue;
used[i] = true;
tempList.add(nums[i]);
backtrack(list, tempList, nums, used);
used[i] = false; //用完后记得置回为false
tempList.remove(tempList.size() - 1);
}
}
}
3. Rotate Image
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
], rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
], rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
思路:本来想根据索引替换规律来解,但是以此遍历整个数组时会出现重复替换的问题。因为顺时针旋转矩阵其实就是将行变成列,再变动列号。所以比较简单的做法是先对矩阵进行转置,然后按列交换矩阵:
The idea was firstly transpose the matrix and then flip it symmetrically. For instance,
1 2 3
4 5 6
7 8 9
after transpose, it will be swap(matrix[i][j], matrix[j][i])
1 4 7
2 5 8
3 6 9
Then flip the matrix horizontally. (swap(matrix[i][j], matrix[i][matrix.length-1-j])
7 4 1
8 5 2
9 6 3
写代码时一个比较麻烦的地方是怎么输入一个矩阵
import java.util.*;
public class LeetCode{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=Integer.parseInt(sc.nextLine());
int[][] matrix=new int[n][n];
for(int i=0;i<n;i++){
String str=sc.nextLine();
String[] strs=str.split(" |,");
for(int j=0;j<n;j++){
matrix[i][j]=Integer.parseInt(strs[j]);
}
}
rotate(matrix);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
}
static void rotate(int[][] matrix) {
for(int i = 0; i<matrix.length; i++){
for(int j = i; j<matrix[0].length; j++){
int temp = 0;
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for(int i =0 ; i<matrix.length; i++){
for(int j = 0; j<matrix.length/2; j++){
int temp = 0;
temp = matrix[i][j];
matrix[i][j] = matrix[i][matrix.length-1-j];
matrix[i][matrix.length-1-j] = temp;
}
}
}
}
LeetCode解题报告—— Permutations & Permutations II & Rotate Image的更多相关文章
- leetcode 解题报告 Word Ladder II
题目不多说了.见https://oj.leetcode.com/problems/word-ladder-ii/ 这一题我反复修改了两天半.尝试过各种思路,总是报TLE.终于知道这一题为什么是leet ...
- LeetCode解题报告:Linked List Cycle && Linked List Cycle II
LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...
- leetcode解题报告(2):Remove Duplicates from Sorted ArrayII
描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...
- LeetCode 解题报告索引
最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
1. Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no ...
- LeetCode解题报告—— Word Search & Subsets II & Decode Ways
1. Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be con ...
- LeetCode解题报告—— Rotate List & Set Matrix Zeroes & Sort Colors
1. Rotate List Given a list, rotate the list to the right by k places, where k is non-negative. Exam ...
- LeetCode解题报告—— Combination Sum & Combination Sum II & Multiply Strings
1. Combination Sum Given a set of candidate numbers (C) (without duplicates) and a target number (T) ...
- LeetCode解题报告—— Sum Root to Leaf Numbers & Surrounded Regions & Single Number II
1. Sum Root to Leaf Numbers Given a binary tree containing digits from 0-9 only, each root-to-leaf p ...
随机推荐
- bzoj2588: Spoj 10628. Count on a tree(树上第k大)(主席树)
每个节点继承父节点的树,则答案为query(root[x]+root[y]-root[lca(x,y)]-root[fa[lca(x,y)]]) #include<iostream> #i ...
- 【learning】杜教筛求欧拉函数前缀和
我们考虑利用\(\sum\limits_{d|n}\varphi(d)=n\)这一性质来处理这个问题 设\(f(n)=\sum\limits_{i=1}^{n}\varphi(i)\) 那么我们可以得 ...
- Django Session配置
Django Session的三种存储方式 SESSION_ENGINE='django.contrib.sessions.backends.db' # default 保存到数据库中,依赖 'dja ...
- 清华大学计算机系大二 java 小学期考试题(摘自知乎)
public class Main { public void test(Object o) { System.out.println("Object"); } public vo ...
- librdkafka 源码分析
http://note.youdao.com/noteshare?id=c7ff510525b4dadaabb6f6a0a72040cc
- OopenCV复习及函数深入理解(轮廓查询及绘图)
核心函数:(后面标明号的,下面有解析) int cvFindContours(Iplimage* img,//这是输入函数,必须是8bit,单通道的图像---1 CvMemStorage* stora ...
- WPF:为什么使用ContentPresenter.ContentSource而不是Content属性?
因为ContentPresenter.ContentSource比Content属性加一个TemplateBinding看起来更方便?不仅仅是这些,实际上如果用ContentSource的话,Cont ...
- ZooKeeper动态配置(十四)
概述 在3.5.0发行之前,ZK的全体成员和所有其它的配置参数是静态加载的在启动的时候并且在运行的时候不可变.操作员诉诸于"滚动重启" - 一个手动密集和改变配置文件容易出错的方法 ...
- 【设计模式】 模式PK:门面模式VS中介者模式
1.概述 门面模式为复杂的子系统提供一个统一的访问界面,它定义的是一个高层接口,该接口使得子系统更加容易使用,避免外部模块深入到子系统内部而产生与子系统内部细节耦合的问题.中介者模式使用一个中介对象来 ...
- web api 支持cors
1. configservice //******************* cors start *********************** var urls = Configuration[S ...