美文网首页
leetcode百题_更新至19-21

leetcode百题_更新至19-21

作者: fjxCode | 来源:发表于2018-11-04 11:52 被阅读0次

Permutations要注意切片取s[:]不安全

题目:

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

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

思路:

  • 排列组合题,用回溯法解。
  • 回溯需要状态,因而不能像 电话号码的题那样用循还。用递归更简便。

一个错误利用切片解:

func permute(nums []int) [][]int {
    res := make([][]int,0)
    resCur := make([]int,0)
    backtracePermute(nums,resCur,&res)
    return res
}

func backtracePermute(nums []int,resCur []int,res *[][]int)  {
    if len(nums) == 0{
        resCur1 := make([]int,len(resCur))
        *res  = append(*res,resCur1)
    }

    for i:=0;i<len(nums);i++{
        numsNew := nums[0:i]
        numsNew = append(numsNew,nums[i+1:]...)
        resCur = append(resCur,nums[i])
        backtracePermute(numsNew,resCur,res)
        resCur = resCur[0:len(resCur)-1]
    }
}

正确解:

func permute(nums []int) [][]int {
    res := make([][]int,0)
    resCur := make([]int,0)
    backtracePermute(nums,&resCur,&res)
    return res
}

func backtracePermute(nums []int,resCur *[]int,res *[][]int)  {
    if len(nums) == 0{
        resCur1 := make([]int,len(*resCur))
        copy(resCur1,*resCur)
        *res  = append(*res,resCur1)
    }

    for i:=0;i<len(nums);i++{
        numsNew := make([]int,0)
        numsNew = append(numsNew,nums[0:i]...)
        numsNew = append(numsNew,nums[i+1:]...)
        *resCur = append(*resCur,nums[i])
        backtracePermute(numsNew,resCur,res)
        *resCur = (*resCur)[0:len(*resCur)-1]
    }
}

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]
]

思路:

  • 实现顺时针旋转。遍历方式0->Y-1;X-1->0,填充至0->X-1,0->Y-1。

解:

func rotate(matrix [][]int)  {
    X := len(matrix)
    Y := len(matrix[0])
    res := make([][]int,X)
    for i:=0;i<X;i++{
        res[i] = make([]int,Y)
    }

    for i:=0;i<Y;i++{
        for j:=X-1;j>=0;j--{
            res[i][X-1-j] = matrix[j][i]
        }
    }

    for i:=0;i<X;i++{
        for j:=0;j<Y;j++{
            matrix[i][j] = res[i][j]
        }
    }
}

相关文章

网友评论

      本文标题:leetcode百题_更新至19-21

      本文链接:https://www.haomeiwen.com/subject/dyyrxqtx.html