LeetCode089 Gray Code

来源:互联网 发布:网络银商 编辑:程序博客网 时间:2024/05/18 15:30

详细见:leetcode.com/problems/gray-code


Java Solution: github

package leetcode;import java.util.HashSet;import java.util.LinkedList;import java.util.List;/* * The gray code is a binary numeral system where two successive values *  differ in only one bit.Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must  begin with 0.For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:00 - 001 - 111 - 310 - 2Note:For a given n, a gray code sequence is not uniquely defined.For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that. */public class P089_GrayCode {public static void main(String[] args) {List<Integer> ans = new Solution().grayCode(0);tools.Utils.B_打印List_Integer(ans);;}/* * WA了一个输入为0 * AC * 5 ms */static class Solution {HashSet<Integer> set = new HashSet<>();List<Integer> ans = new LinkedList<Integer>();int[] arr = null;int count = 0, n = 0, set_max_size = 0;boolean isDone = false;    public List<Integer> grayCode(int n) {        if (n < 0) {        return ans;        }        this.n = n;        set_max_size = 1 << n;        arr = new int[n];        ans.add(0);        set.add(0);        search();        return ans;    }private void search() {if (set.size() == set_max_size) {isDone = true;return;}if (isDone) {return;}for (int i = n - 1;! isDone &&  i > -1; i --) {arr[i] = arr[i] == 0 ? 1 : 0;if (add()) {search();}arr[i] = arr[i] == 0 ? 1 : 0;}}private boolean add() {int val = 0;for (int i = 0; i != arr.length; i ++) {val = val * 2 + arr[i];}if (! set.contains(val)) {ans.add(val);set.add(val);return true;} else {return false;}}}}


C Solution: github

/*    url: leetcode.com/problems/gray-code    AC 3ms 26.92%*/#include <stdio.h>#include <stdlib.h>int* grayCode(int n, int* rn) {    int* a = NULL, ai = 0;    int* r = NULL, ri = 0, v = 0, *t = NULL;    int an = 1 << n;    if (n < 1) {        *rn = 1;        a = (int*) malloc(sizeof(int) * 1);        a[0] = 0;        return a;    }    a = (int*) malloc(sizeof(int) * an);    r = (int*) malloc(sizeof(int) * n);    t = (int*) malloc(sizeof(int) * n);    v = 2;    for (ri = n-1; ri > -1; ri --) {        r[ri] = v;        t[ri] = -v/2;        v <<= 1;    }    while (1) {        v = 0;        for (ri = 0; ri < n; ri ++)             if (t[ri] > 0) v += r[ri]/2;        a[ai ++] = v;        if (ai == an) break;        for (ri = 0; ri < n; ri ++) {            if (t[ri] > 0) {                t[ri] --;                if (t[ri] == 0) t[ri] = -r[ri];            } else {                t[ri] ++;                if (t[ri] == 0) t[ri] = r[ri];            }        }    }    *rn = an;    return a;}int main() {    int n = 3;    int rn = 0;    int* a = grayCode(n, &rn);    int i = 0;    for (i = 0; i < rn; i ++)        printf("%d\r\n", a[i]);    free(a);    return 0;}


Python Solution: github

#coding=utf-8'''    url: leetcode.com/problems/gray-code    @author:     zxwtry    @email:      zxwtry@qq.com    @date:       2017年4月22日    @details:    Solution: 62ms 26.96%'''class Solution(object):    def grayCode(self, n):        """        :type n: int        :rtype: List[int]        """        s, r, v, a = [0]*n, [0]*n, 2, []        for i in range(n-1, -1, -1):            s[i] = v            r[i] = -v / 2            v *= 2        for v in range(1 << n):            val = 0            for i in range(n):                val = val * 2 + (0 if r[i]<0 else 1)            a.append(val)            for i in range(n):                if r[i] > 0:                    r[i] -= 1                    if r[i] == 0: r[i] = -s[i]                else:                    r[i] += 1                    if r[i] == 0: r[i] = s[i]        return aif __name__ == "__main__":    print(Solution().grayCode(3))                    


0 0