leetcode百题_更新至19-21

2018-11-04  本文已影响0人  fjxCode

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

思路:

解:

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]
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读