I really think this problem shouldn't be put under category "Backtracking"!


  • 0
    B

    There is a more effective solution than backtracking which is more intuitive:

    public class Solution {
        public List<Integer> grayCode(int n) {
            List<Integer> result = new ArrayList<>();
            result.add(0);
            if(n == 0) return result;
            for(int i = 0;i<n;++i){
                int inc = 1<<i;
                for(int j = result.size()-1;j>=0;--j) result.add(inc + result.get(j));
            }
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.